自定义注解
使用场景
Java自定义注解一般使用场景为:自定义注解+拦截器或者AOP,使用自定义注解来自己设计框架,使得代码看起来非常优雅。
自定义注解+拦截器
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation{
String type();
String secondaryType();
}
注解的处理是通过java反射来处理的。如下,反射相关的类Class, Method, Field都实现了AnnotationElement接口。
应用场景一:自定义注解+拦截器
- 实现spring的HandlerInterceptor 类先实现拦截器
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
// 反射获取方法上的MyAnnotation 注解
HandlerMethod handlerMethod = (HandlerMethod)handler;
MyAnnotation myAnnotation= handlerMethod.getMethod().getAnnotation(MyAnnotation.class);
if(myAnnotation== null){
return true;
}
// 有MyAnnotation 注解
response.setContentType("application/json; charset=utf-8");
response.getWriter().print("你访问的资源xxxx");
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
- 实现spring类WebMvcConfigurer,创建配置类把拦截器添加到拦截器链中
public class MyInterceptorConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry interceptorRegistry) {
interceptorRegistry.addInterceptor(new SourceAccessInterceptor()).addPathPatterns("/**");
}