Spring 自定义注解精要解释

default

示例

  • 注解
1
2
3
4
5
6
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface LogHandle {
    String value() default "";
}
  • 方法加注解
1
2
3
4
@LogHandle("helloworld")
public void helloworld(){
    
}
  • 拦截器
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
@Slf4j
@Component
public class TransactionLogInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        ApiOperation methodAnnotation = handlerMethod.getMethodAnnotation(LogHandle.class);
        if (methodAnnotation != null){
            Method method = handlerMethod.getMethod();
            log.info("{}-{}", method.getName(), methodAnnotation.value());
        }
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
  • 注册拦截器
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private TokenInterceptor tokenInterceptor;

    @Autowired
    private TransactionLogInterceptor transactionLogInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(transactionLogInterceptor);
}

注解参数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@Target(ElementType.TYPE)
1.CONSTRUCTOR:用于描述构造器
2.FIELD:用于描述域
3.LOCAL_VARIABLE:用于描述局部变量
4.METHOD:用于描述方法
5.PACKAGE:用于描述包
6.PARAMETER:用于描述参数
7.TYPE:用于描述类接口(包括注解类型) 或enum声明

@Retention(RetentionPolicy.RUNTIME)
1.SOURCE:在源文件中有效即源文件保留
2.CLASS:在class文件中有效即class保留
3.RUNTIME:在运行时有效即运行时保留

@Documented
可以被例如javadoc此类的工具文档化

@Inherited
如果一个使用了@Inherited修饰的annotation类型被用于一个class则这个annotation将被用于该class的子类
Gear(夕照)的博客。记录开发、生活,以及一些不足为道的思考……