1. 概念
1.1 元注解
元注解的作用就是负责注解其他注解。java5.0定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明
java5.0定义的元注解:java.lang.annotation包
- @target:描述了注解修饰的对象范围
- @retention:表示注解保留时间长短
- @documented:表示是否将此注解的相关信息添加到javadoc文档中
- @inherited:是否允许子类继承该注解,只有在类上使用时才会有效,对方法,属性等其他无效
1.1.1 target
描述了注解修饰的对象范围
取值在java.lang.annotation.elementtype定义,常用的包括:
- method:用于描述方法
- package:用于描述包
- parameter:用于描述方法变量
- type:用于描述类、接口或enum类型
- constructor:用于描述构造器
- field:用于描述域
- local_variable:用于描述局部变量
- type_parameter:类型参数,表示这个注解可以用在 type的声明式前,jdk1.8引入
- type_use:类型的注解,表示这个注解可以用在所有使用type的地方(如:泛型,类型转换等),jdk1.8引入
elementtype 源码:
public enum elementtype { /** class, interface (including annotation type), or enum declaration */ type, /** field declaration (includes enum constants) */ field, /** method declaration */ method, /** formal parameter declaration */ parameter, /** constructor declaration */ constructor, /** local variable declaration */ local_variable, /** annotation type declaration */ annotation_type, /** package declaration */ package, /** * type parameter declaration * * @since 1.8 */ type_parameter, /** * use of a type * * @since 1.8 */ type_use }
1.1.1.1 示例
注解table 可以用于注解类、接口(包括注解类型) 或enum声明
注解nodbcolumn仅可用于注解类的成员变量。
@target(elementtype.type) public @interface table { /** * 数据表名称注解,默认值为类名称 * @return */ public string tablename() default "classname"; } @target(elementtype.field) public @interface nodbcolumn { }
1.1.2 retention
表示注解保留时间长短
取值在java.lang.annotation.retentionpolicy中,取值为:
- source:在源文件中有效,编译过程中会被忽略
- class:随源文件一起编译在class文件中,运行时忽略
- runtime:在运行时有效
只有定义为retentionpolicy.runtime时,我们才能通过注解反射获取到注解。
1.1.2.1 示例
@target(elementtype.field) @retention(retentionpolicy.runtime) public @interface column { public string name() default "fieldname"; public string setfuncname() default "setfield"; public string getfuncname() default "getfield"; public boolean defaultdbvalue() default false; }
1.1.3 documented
描述其它类型的annotation应该被作为被标注的程序成员的公共api,因此可以被例如javadoc此类的工具文档化。
documented是一个标记注解,没有成员
表示是否将此注解的相关信息添加到javadoc文档中
1.1.4 inherited
定义该注解和子类的关系,使用此注解声明出来的自定义注解,在使用在类上面时,子类会自动继承此注解,否则,子类不会继承此注解。
注意:
- 使用inherited声明出来的注解,只有在类上使用时才会有效,对方法,属性等其他无效。
- @inherited annotation类型是被标注过的class的子类所继承。类并不从它所实现的接口继承annotation,方法并不从它所重载的方法继承annotation。
- 类型标注的annotation的retention是retentionpolicy.runtime,如果我们使用java.lang.reflect去查询一个@inherited annotation类型的annotation时,反射代码检查将展开工作:检查class和其父类,直到发现指定的annotation类型被发现,或者到达类继承结构的顶层。
1.1.4.1 示例
@inherited public @interface greeting { public enum fontcolor{ bule,red,green}; string name(); fontcolor fontcolor() default fontcolor.green; }
1.2 自定义注解
@interface用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数
- 方法的名称就是参数的名称,
- 返回值类型就是参数的类型(返回值类型只能是基本类型、class、string、enum)
- 可以通过default来声明参数的默认值。
1.2.1 使用格式
public @interface 注解名 {定义体}
1.2.2 支持数据类型
注解参数可支持数据类型:
- 所有基本数据类型(int,float,boolean,byte,double,char,long,short)
- string类型
- class类型
- enum类型
- annotation类型
- 以上所有类型的数组
annotation类型里面的参数该怎么设定:
- 只能用public或默认(default)这两个访问权修饰.例如,string value();这里把方法设为defaul默认类型、
- 参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和 string,enum,class,annotations等数据类型,以及这一些类型的数组
例如,string value();这里的参数成员就为string;
如果只有一个参数成员,最好把参数名称设为"value",后加小括号.
例:下面的例子fruitname注解就只有一个参数成员。
@target(elementtype.field) @retention(retentionpolicy.runtime) @documented public @interface fruitname { string value() default ""; }
1.2.3 注解元素的默认值
注解元素必须有确定的值,要么在定义注解的默认值中指定,要么在使用注解时指定,非基本类型的注解元素的值不可为null
- 使用空字符串或0作为默认值是一种常用的做法
- 这个约束使得处理器很难表现一个元素的存在或缺失的状态,因为每个注解的声明中,所有元素都存在,并且都具有相应的值,为了绕开这个约束,我们只能定义一些特殊的值,例如空字符串或者负数,一次表示某个元素不存在,在定义注解时,这已经成为一个习惯用法。
1.3 为什么要使用自定义注解
语义清晰:自定义注解可以使代码的意图更加明确和可读。
例如,使用 @transactional 注解可以清晰地表明某个方法需要事务支持,而不需要查看aop配置或切面代码。
- 简化配置:可以简化配置,减少样板代码。通过注解,开发者可以直接在代码中声明需要的行为,而不需要在外部配置文件中进行复杂的配置
- 增强可维护性:注解使得代码更加模块化和可维护。开发者可以通过注解快速定位和理解代码的行为,而不需要深入理解aop的实现细节
- 灵活性:自定义注解可以与aop结合使用,提供更灵活的解决方案。例如,可以定义多个注解来表示不同的切面逻辑,然后在切面中根据注解类型进行不同的处理。
2. 使用注意
2.1 不生效情况
保留策略不正确:注解可能在运行时不可见。
- 解决方法:确保注解的保留策略设置为 retentionpolicy.runtime,这样注解在运行时可通过反射获取。
目标元素不正确:目标元素(target element)设置不正确,注解可能无法应用到期望的程序元素上。
- 解决方法:确保注解的目标元素设置正确,例如 elementtype.method、elementtype.field 等
未启用aop:如果使用aop来处理注解,但未启用aop支持,注解处理逻辑将不会生效
解决方法:确保在spring boot应用的主类上添加 @enableaspectjautoproxy 注解。
import org.springframework.boot.springapplication; import org.springframework.boot.autoconfigure.springbootapplication; import org.springframework.context.annotation.enableaspectjautoproxy; @springbootapplication @enableaspectjautoproxy public class application { public static void main(string[] args) { springapplication.run(application.class, args); } }
spring boot的自动配置机制会根据类路径中的依赖和配置文件中的属性自动配置许多常见的功能。
例如,spring-boot-starter-aop 依赖会自动启用aop支持
切面未被spring管理:如果切面类未被spring管理,aop切面将不会生效。
- 解决方法:确保切面类上添加了 @component 注解,或者通过其他方式将其注册为spring bean。
import org.aspectj.lang.annotation.aspect; import org.springframework.stereotype.component; @aspect @component public class myaspect { // 切面逻辑 }
注解处理逻辑有误:如果注解处理逻辑有误,注解可能不会按预期生效。
- 解决方法:检查注解处理逻辑,确保正确处理注解。例如,使用反射获取注解时,确保方法签名和注解类型正确。
import java.lang.reflect.method; public class main { public static void main(string[] args) throws exception { method method = myclass.class.getmethod("mymethod"); myannotation annotation = method.getannotation(myannotation.class); if (annotation != null) { // 处理注解 } } }
注解未正确应用:如果注解未正确应用到目标元素上,注解将不会生效。
- 解决方法:确保注解正确应用到目标元素上,例如方法、字段、类等。
public class myclass { @myannotation public void mymethod() { // 方法实现 } }
2.2 其他
自定义注解可以在java和spring项目中使用。具体来说:
- java:java本身提供了注解的功能,允许开发者定义和使用自定义注解。自定义注解可以用于代码文档、编译时检查、运行时行为等。
- spring:spring框架广泛使用注解来配置和管理bean、事务、aop等。你可以在spring项目中定义自定义注解,并结合spring的功能(如aop、依赖注入等)来实现特定的业务逻辑。
因此,自定义注解既可以用于纯java项目,也可以用于spring项目。具体取决于你的需求和项目类型。
3. 实例
3.1 自定义注解 实现赋值和校验
定义两个注解,一个用来赋值,一个用来校验。
@documented @retention(retentionpolicy.runtime) @target({elementtype.field,elementtype.method}) @inherited public @interface initsex { enum sex_type {man, woman} sex_type sex() default sex_type.man; }
@documented @retention(retentionpolicy.runtime) @target({elementtype.field,elementtype.method}) @inherited public @interface validateage { /** * 最小值 */ int min() default 18; /** * 最大值 */ int max() default 99; /** * 默认值 */ int value() default 20; }
定义user类
@data public class user { private string username; @validateage(min = 20, max = 35, value = 22) private int age; @initsex(sex = initsex.sex_type.man) private string sex; }
测试调用
public static void main(string[] args) throws illegalaccessexception { user user = new user(); inituser(user); boolean checkresult = checkuser(user); printresult(checkresult); } static boolean checkuser(user user) throws illegalaccessexception { // 获取user类中所有的属性(getfields无法获得private属性) field[] fields = user.class.getdeclaredfields(); boolean result = true; // 遍历所有属性 for (field field : fields) { // 如果属性上有此注解,则进行赋值操作 if (field.isannotationpresent(validateage.class)) { validateage validateage = field.getannotation(validateage.class); field.setaccessible(true); int age = (int) field.get(user); if (age < validateage.min() || age > validateage.max()) { result = false; system.out.println("年龄值不符合条件"); } } } return result; } static void inituser(user user) throws illegalaccessexception { // 获取user类中所有的属性(getfields无法获得private属性) field[] fields = user.class.getdeclaredfields(); // 遍历所有属性 for (field field : fields) { // 如果属性上有此注解,则进行赋值操作 if (field.isannotationpresent(initsex.class)) { initsex init = field.getannotation(initsex.class); field.setaccessible(true); // 设置属性的性别值 field.set(user, init.sex().tostring()); system.out.println("完成属性值的修改,修改值为:" + init.sex().tostring()); } } }
3.2 自定义注解+拦截器 实现登录校验
如果方法上加了@loginrequired,则提示用户该接口需要登录才能访问,否则不需要登录。
定义自定义注解:loginrequired
@target(elementtype.method) @retention(retentionpolicy.runtime) public @interface loginrequired { }
定义两个简单的接口
@restcontroller public class testcontroller { @getmapping("/sourcea") public string sourcea(){ return "你正在访问sourcea资源"; } @loginrequired @getmapping("/sourceb") public string sourceb(){ return "你正在访问sourceb资源"; } }
实现spring的handlerinterceptor 类,重写prehandle实现拦截器,登录拦截逻辑
@slf4j public class sourceaccessinterceptor implements handlerinterceptor { @override public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception { log.info("进入拦截器了"); // 反射获取方法上的loginrequred注解 handlermethod handlermethod = (handlermethod)handler; loginrequired loginrequired = handlermethod.getmethod().getannotation(loginrequired.class); if(loginrequired == null){ return true; } // 有loginrequired注解说明需要登录,提示用户登录 response.setcontenttype("application/json; charset=utf-8"); response.getwriter().print("你访问的资源需要登录"); return false; } @override public void posthandle(httpservletrequest request, httpservletresponse response, object handler, modelandview modelandview) throws exception { } @override public void aftercompletion(httpservletrequest request, httpservletresponse response, object handler, exception ex) throws exception { }}
实现spring类webmvcconfigurer,创建配置类把拦截器添加到拦截器链中
@configuration public class interceptortrainconfigurer implements webmvcconfigurer { @override public void addinterceptors(interceptorregistry registry) { registry.addinterceptor(new sourceaccessinterceptor()).addpathpatterns("/**"); } }
3.3 自定义注解+aop 实现日志打印
切面需要的依赖包
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-aop</artifactid> </dependency>
自定义注解@mylog
@target(elementtype.method) @retention(retentionpolicy.runtime) public @interface mylog{ }
定义切面类
@aspect // 1.表明这是一个切面类 @component public class mylogaspect { // 2. pointcut表示这是一个切点,@annotation表示这个切点切到一个注解上,后面带该注解的全类名 // 切面最主要的就是切点,所有的故事都围绕切点发生 // logpointcut()代表切点名称 @pointcut("@annotation(me.zebin.demo.annotationdemo.aoplog.mylog)") public void logpointcut(){}; // 3. 环绕通知 @around("logpointcut()") public void logaround(proceedingjoinpoint joinpoint){ // 获取方法名称 string methodname = joinpoint.getsignature().getname(); // 获取入参 object[] param = joinpoint.getargs(); stringbuilder sb = new stringbuilder(); for(object o : param){ sb.append(o + "; "); } system.out.println("进入[" + methodname + "]方法,参数为:" + sb.tostring()); // 继续执行方法 try { joinpoint.proceed(); } catch (throwable throwable) { throwable.printstacktrace(); } system.out.println(methodname + "方法执行结束"); } }
使用
@mylog @getmapping("/sourcec/{source_name}") public string sourcec(@pathvariable("source_name") string sourcename){ return "你正在访问sourcec资源"; }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论