当前位置: 代码迷 >> 综合 >> Spring自定义注解学习
  详细解决方案

Spring自定义注解学习

热度:103   发布时间:2023-10-09 03:00:11.0

spring中有很多的注解使我们开发过程更加简洁方便。
这些注解的本质也是一个一个的java类与接口的实现。
他们具体是怎么实现的呢,在前几天学习的时候,我无意间看到了一个类的泛型叫做@interface,很有意思,学习之后发现他原来就是用来定义注解类的。
使用了@interface泛型就会被框架默认为继承了Annotation接口。
之后我们就可以自定义一个注解类来实现一些好玩的东西了,比如初始化赋值,或者在注解解析器里进行一些数据校验等等。
这样做比每个类都要继承父类或者实现接口要方便一些。
还可以应用到aop切面中,进行一些日志的管理等等。

话不多说,放码过来:

第一步,把冰箱门··咳咳···自定义一个注解类;

import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;//注解包含在javadoc中:
@Documented
//注解可以被继承
@Inherited
//目标:
//ElementType.ANNOTATION_TYPE:可以给注解进行注解
//ElementType.CONSTRUCTOR:可以给构造方法进行注解
//ElementType.FIELD:可以给字段进行注解
//ElementType.LOCAL_VARIABLE:可以给局部变量进行注解
//ElementType.METHOD:可以给方法进行注解
//ElementType.PACKAGE:可以给包进行注解
//ElementType.PARAMETER:可以给方法内的参数进行注解
//ElementType.TYPE:可以给类型进行注解,比如类、接口和枚举
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public  @interface Something {//使用@interface声明自己是个注解类,自定义一个注解public String xx() default "666";}

第二步:把大象···

import java.lang.reflect.Field;
import java.lang.reflect.Method;public class Todo {@Something(xx = "33")//如果一个@Something中只有一个属性名字叫value,那么可以@Something("33")的格式赋值public static String data;//	
//	public static String getData() {
//		return data;
//	}
//	
//	public static void setData(String data) {
//		test3.data = data;
//	}public static void main(String[] args) {create();System.out.println(data);}public static Todo create(){Todo user = new Todo();// 获取Something类中所有的方法(getDeclaredMethods也行)//  Method[] methods = Todo.class.getMethods();Field[] fields = Todo.class.getFields();try{//获取应用到使用类的方法上的注解
//	            for (Method method : methods){
//	                // 如果此方法有注解,就把注解里面的数据赋值到user对象
//	                if (method.isAnnotationPresent(Something.class)){
//	                	Something Something = method.getAnnotation(Something.class);
//	                    method.invoke(user, Something.xx());
//	                }
//	            }//获取应用到使用类的属性上的注解for (Field field : fields) {if (field.isAnnotationPresent(Something.class)){Something Something = field.getAnnotation(Something.class);field.set(user, Something.xx());}}}catch (Exception e){e.printStackTrace();return null;}return user;}
}

@Something(xx="33")的输出结果是33;

@Something的输出结果是666;

  相关解决方案