在整个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 {}; }
/*源码级别*/ // 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); } }
重点需要关注的是:切点的定义,切点可以定义成execute(public String sayHello()) 的形式,但是这种形式就和咱们的注解不相关了,因此我们采用@annotation(MyFirstAnnotation) 的形式,这样切点就变成了我们自定义注解所修饰的方法
第四步:使用自定义注解
@MyFirstAnnotation("吃饭") @RequestMapping(value = "/say") public String sayHello() { System.out.println("吃饭"); return "hello spring boot"; }
控制台结果输出:
准备吃饭 吃饭 结束吃饭
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/225986.html原文链接:https://javaforall.net
