一、@interface 关键字
我们想定义一个自己的注解 需要使用 @interface 关键字来定义。
如定义一个叫 myannotation 的注解:
public @interface myannotation { }
二、元注解
光加上 @interface 关键字 还不够,我们还需要了解5大元注解
@retention
@target
@documented
@inherited(jdk8 引入)
@repeatable(jdk8 引入)
1) @retention 指定注解的生命周期
@retention(retentionpolicy.source)
其中retention是一个枚举类:
- retentionpolicy.source : 注解只保留在源文件,当java文件编译成class文件的时候,注解被遗弃(.java文件)
- retentionpolicy.class :注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期(.class文件)
- retentionpolicy.runtime: 注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在(内存中的字节码)
2) @target指定注解可以修饰的元素类型
@target(elementtype.field)
- elementtype.annotation_type - 标记的注解可以应用于注解类型。
- elementtype.constructor - 标记的注解可以应用于构造函数。
- elementtype.field - 标记的注解可以应用于字段或属性。
- elementtype.local_variable - 标记的注解可以应用于局部变量。
- elementtype.method - 标记的注解可以应用于方法。
- elementtype.package - 标记的注解可以应用于包声明。
- elementtype.parameter - 标记的注解可以应用于方法的参数。
- elementtype.type - 标记的注解可以应用于类的任何元素。
3)@documented指定注解会被javadoc工具提取成文档。默认情况下,javadoc是不包括文档的
4)@inherited表示该注解会被子类继承,注意,仅针对类,成员属性、方法并不受此注释的影响。
5)@repeatable表示注解可以重复使用,为了解决同一个注解不能重复在同一类/方法/属性上使用的问题。
其中最常用的就是 @retention 跟 @target。
三、简单实现
例如实现一个简单,在标记注解的地方打印一句日志。
定义一个 myannotation 注解,并且定义一个属性 message 默认值是 ”aaa“。先将该注解加到字段上,看能不能获取到。
//注解用于字段上 @target(elementtype.field) //运行时使用 @retention(retentionpolicy.runtime) public @interface myannotation { string message() default "aaa"; }
定义一个student类用于测试:
@data public class student { @jsonfield(ordinal =0) @myannotation(message = "aaaaaaaaa") public string name; @myannotation(message = "aaaaaaaaa") public integer score; }
在字段上标注该注解,然后编写一个main方法获取该注解的属性:
public static void main(string[] args) { class<?> studentclass = student.class; field[] fields = studentclass.getdeclaredfields();//获取所有的类成员变量字段 for (field field : fields) { string fieldname = field.getname(); //获取该类成员变量的名字 system.out.println("成员变量名是:" + fieldname); annotation[] annotations = field.getannotations(); //获取该类成员变量上所有声明周期是运行时的注解 for (annotation annotation : annotations) { class<? extends annotation> annotationtype = annotation.annotationtype(); string annotationname = annotationtype.getsimplename();//注解的简短名称 system.out.println(" 使用的注解是:" + annotationname); //判断该注解是不是 myannotation 注解,是的话打印其 id 和 describe 属性 if (annotationtype.equals(myannotation.class)) { myannotation myannotation = field.getannotation(myannotation.class); string message = myannotation.message(); system.out.println(" myannotation注解中的message是:" + message); } } system.out.println(); } }
执行后打印的内容:
以上就是一个注解的简单实现。
四、使用切面执行自定义注解逻辑
在开发中一般加上注解之后会自动执行一些逻辑,大部分实现的原理是使用切面来实现注解的逻辑的。
1) 首先将刚才的注解修改成放在方法上的:
//注解用于方法 @target(elementtype.method) //运行时使用 @retention(retentionpolicy.runtime) public @interface myannotation { string message() default "aaa"; }
2) 定义一个切面类:
@component @aspect @slf4j public class myannotationaspect { /* * 这是一个切入点 * */ @pointcut("@annotation(com.demo.aaa.annotation.myannotation)") public void cutmethod(){ } /** * 切点之前 */ @before("cutmethod()") public void before(joinpoint joinpoint) throws throwable { log.info("============ before =========="); } /** * 切点之后 */ @after("cutmethod()") public void after() throws throwable { log.info("============ after =========="); } /** * 切点返回内容后 */ @afterreturning("cutmethod()") public void afterreturning() throws throwable { log.info("============ afterreturning =========="); } /** * 切点抛出异常后 */ @afterthrowing("cutmethod()") public void afterthrowing() throws throwable { log.info("============ afterthrowing =========="); } @around("cutmethod() && @annotation(myannotation)") public object around(proceedingjoinpoint point, myannotation myannotation) throws throwable { log.info("============ around1 =========="); object obj= point.proceed(point.getargs()); log.info("============ around2 =========="); return obj; } }
在使用aop之前需要先引入一个依赖:
<dependency> <groupid>org.aspectj</groupid> <artifactid>aspectjweaver</artifactid> <version>1.8.13</version> </dependency>
简单说一下各个注解代表什么含义:
- @aspect:作用是把当前类标识为一个切面供容器读取 ,也就是加上这个注解,spring才知道你这是一个切面类,用于处理切点的逻辑的。
- @pointcut:切入点,@pointcut切点表达式非常丰富,可以将 方法(method)、类(class)、接口(interface)、包(package) 等作为切入点,非常灵活,常用的有@annotation、@within、execution等方式,上面的示例使用的是@annotation方式,意思就是说被spring扫描到方法上带有@annotation中的注解 就会执行切面通知。
- @before:该注解标注的方法在业务模块代码执行之前执行,其不能阻止业务模块的执行,除非抛出异常;
- @afterreturning:该注解标注的方法在业务模块代码执行之后执行;
- @afterthrowing:该注解标注的方法在业务模块抛出指定异常后执行;
- @after:该注解标注的方法在所有的 advice 执行完成后执行,无论业务模块是否抛出异常,类似于 finally 的作用;
- @around:该注解功能最为强大,其所标注的方法用于编写包裹业务模块执行的代码,通知的第一个参数必须是 proceedingjoinpoint 类型。在通知体内,调用 proceedingjoinpoint 的 proceed () 方法使得连接点方法执行如果不调用 proceed () 方法,连接点方法则不会执行。无论是调用前逻辑还是调用后逻辑,都可以在该方法中编写,甚至其可以根据一定的条件而阻断业务模块的调用; 如果切面中使用了@around 注解,如果不调用 proceedingjoinpoint 的 proceed () 方法的话,那么 @before 和 @after 直接标注的方法也不会被触发。@around 注解标注的方法,在 proceedingjoinpoint 的 proceed () 方法 前的逻辑是比@before的逻辑还要靠前, 在proceed () 方法之后的逻辑比 @after 的逻辑还要靠后。
- joint point:jointpoint是程序运行过程中可识别的点,这个点可以用来作为aop切入点。jointpoint对象则包含了和切入相关的很多信息。比如切入点的对象,方法,属性等。我们可以通过反射的方式获取这些点的状态和信息,用于追踪tracing和记录logging应用信息。
3)将注解放入到接口方法中测试:
@getmapping("/aaa") @myannotation(message = "成功拉!!!!!!!!!!!!") public void test() { system.out.println("执行代码逻辑"); }
调用接口之后打印
上面就是自定义注解最简单的示例。
五、切点表达式
我们定义切点除了使用 @pointcut() 之外,我们还有丰富的切点表达式可以定义切点。
1)切点表达式简介
2)通配符合与逻辑运算符
@aspectj 支持三种通配符:
逻辑运算符: 切点表达式由切点函数组成,切点函数之间还可以进行逻辑运算,组成复合切点。
3)切点表达式:
1.arg() :匹配切入点方法的参数类型,匹配的上才是切点。
语法:args(param-pattern) param-pattern:参数类型的全路径。
注意:要先匹配到某些类,不然会报错,也就是不能单独用
示例:
@pointcut("args(java.lang.string)") //这样就是错的,不能单独使用要匹配到某些类 @pointcut("within(com.example.demo.service.impl.userserviceimpl) && args(java.lang.string,java.lang.string)") //要像这样使用 within 先匹配到某个具体的类,在使用args匹配到某个类型参数的方法
2.@args:匹配切入点方法上的参数的类上,参数的类必须要有指定的注解
语法:@args(annotation-type) annotation-type:注解类型的全路径
注意:也不能单独使用,必须先指定到类,而且匹配参数个数至少有一个且为第一个参数的类含有该注解才能匹配的上
示例:
@pointcut("within(com.demo.redistest) && @args(com.demo.aaa.annotation.myannotation)")
3.within:匹配切入点的指定类的任意方法,不能匹配接口。
语法:within(declaring-type) 参数为全路径的类名(可使用通配符),表示匹配当前表达式的所有类都将被当前方法环绕
注意: 这个是指定到具体的类
示例:
//within表达式的粒度为类,其参数为全路径的类名(可使用通配符),表示匹配当前表达式的所有类都将被当前方法环绕。如下是within表达式的语法: @pointcut(within(declaring-type-pattern)) //within表达式只能指定到类级别,如下示例表示匹配com.spring.service.businessobject中的所有方法: @pointcut(within(com.spring.service.businessobject)) //within表达式路径和类名都可以使用通配符进行匹配,比如如下表达式将匹配com.spring.service包下的所有类,不包括子包中的类: @pointcut(within(com.spring.service.*)) //如下表达式表示匹配com.spring.service包及子包下的所有类: @pointcut(within(com.spring.service..*))
4.@within:表示匹配带有指定注解的类。
语法:@within(annotation-type) 注解的全类名
注意:这个是指定到带有某个注解的类
示例:
//如下所示示例表示匹配使用com.spring.annotation.businessaspect注解标注的类: @within(com.spring.annotation.businessaspect)
5.@annotation() :匹配带有指定注解的连接点
语法:@annotation(annotation-type) annotation-type:注解类型的全路径
示例:
@pointcut("@annotation(com.test.annotations.logauto)")
6.execution() 用于匹配是连接点的执行方法,spring 切面粒度最小是达到方法级别,而 execution 表达式可以用于明确指定方法返回类型,类名,方法名和参数名等与方法相关的配置,所以是使用最广泛的。
用法:
- modifiers-pattern:方法的可见性修饰符,如 public,protected,private;
- ret-type-pattern:方法的返回值类型,如 int,void 等;
- declaring-type-pattern:方法所在类的全路径名,如 com.spring.aspect;
- name-pattern:方法名,如 getorderdetail();
- param-pattern:方法的参数类型,如 java.lang.string;
- throws-pattern:方法抛出的异常类型,如 java.lang.exception;
示例:
modifiers-pattern:方法的可见性修饰符,如 public,protected,private; ret-type-pattern:方法的返回值类型,如 int,void 等; declaring-type-pattern:方法所在类的全路径名,如 com.spring.aspect; name-pattern:方法名,如 getorderdetail(); param-pattern:方法的参数类型,如 java.lang.string; throws-pattern:方法抛出的异常类型,如 java.lang.exception; 示例: // 匹配目标类的所有 public 方法,第一个 * 代表返回类型,第二个 * 代表方法名,..代表方法的参数 execution(public * *(..)) // 匹配目标类所有以 user 为后缀的方法。第一个 * 代表返回类型,*user 代表以 user 为后缀的方法 execution(* *user(..)) // 匹配 user 类里的所有方法 execution(* com.test.demo.user.*(..)) // 匹配 user 类及其子类的所有方法 execution(* com.test.demo.user+.*(..)) : // 匹配 com.test 包下的所有类的所有方法 execution(* com.test.*.*(..)) // 匹配 com.test 包下及其子孙包下所有类的所有方法 execution(* com.test..*.*(..)) : // 匹配 getorderdetail 方法,且第一个参数类型是 long,第二个参数类型是 string execution(* getorderdetail(long, string))
六、切面中获取各个参数
示例:
@around(value = "@annotation(basislogannotation)") public object demoaop(proceedingjoinpoint proceedingjoinpoint, final basislogannotation basislogannotation) throws throwable { logger.debug("执行前:"); object object = proceedingjoinpoint.proceed(); //执行连接点方法,object:方法返回值 logger.debug("执行后:"); // 类名 string classname = proceedingjoinpoint.gettarget().getclass().getname(); //方法名 string methodname = proceedingjoinpoint.getsignature().getname(); //参数(我这里是对象,具体根据个人的参数类型来强转) basisuser basisuser = (basisuser)proceedingjoinpoint.getargs()[0]; return object; }
总结
到此这篇关于java如何实现自定义注解的文章就介绍到这了,更多相关java自定义注解内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论