springboot学习-----自定义注解
在整个spring框架中,提供的注解非常的多,这些注解简化了我们的很多操作。那么,我们如何自定义注解呢?
第一步:学习已有的注解
@Target({
ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
String name() default "";
@AliasFor("path")
String[] value() default {
};
@AliasFor("value")
String[] path() default {
};
RequestMethod[] method() default {
};
String[] params() default {
};
String[] headers() default {
};
String[] consumes() default {
};
String[] produces() default {
};
}
这是RequestMapping的注解,这个注解里包含了4个其他的注解,我大致介绍一下(其实源码里面说的很清楚):
1.@Target
定义注解修饰的目标,比如@RequestMapping 就是用来修饰方法和类
2.@Retention
定义注解的生命周期,分为以下三种:
/*源码级别*/ // Annotations are to be discarded by the compiler. SOURCE, /*编译期级别*/ /*Annotations are to be recorded in the class file by the compiler,but need not be retained by the VM at run time. This is the defaultbehavior.*/ CLASS, /*运行期级别*/ /*Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively. RUNTIME
3.@Documented
定义注解会被javadoc或者其他类似工具文档化
4.@Mapping
定义注解是一个web mapping annotation
第二步:创建自定义注解
@Target({
ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyFirstAnnotation {
String value() default "";
}
第三步:定义切面类
创建完自定义注解后,很显然的思路是如何让注解起作用。这里以输出日志的注解为例,当用自定义注解来修饰方法时,我们期望在方法执行的前后输出日志记录,那么我们必须采用AOP(面向切面编程)的思想,理所当然地,我们需要定义切面类:
@Aspect
@Component
public class MyFirstAspect {
@Pointcut("@annotation(MyFirstAnnotation)")
public void annotationPointcut() {
}
@Before("annotationPointcut()")
public void beforePointcut(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
MyFirstAnnotation annotation = method.getAnnotation(MyFirstAnnotation.class);
String value = annotation.value();
System.out.println("准备"+value);
}
@After("annotationPointcut()")
public void afterPointcut(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
MyFirstAnnotation annotation = method.getAnnotation(MyFirstAnnotation.class);
String value = annotation.value();
System.out.println("结束"+value);
}
}
第四步:使用自定义注解
@MyFirstAnnotation("吃饭")
@RequestMapping(value = "/say")
public String sayHello() {
System.out.println("吃饭");
return "hello spring boot";
}
控制台结果输出:
准备吃饭 吃饭 结束吃饭
下一篇:
VS快捷键大全(超详细)
