springboot 实现自定义注解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nihaoa50/article/details/85244904

1、定义一个注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Test {

}

注意:

  • @Target
    • ElementType.TYPE:接口、类、枚举、注解
    • ElementType.FIELD:字段、枚举的常量
    • ElementType.METHOD:方法
    • ElementType.PARAMETER:方法参数
    • ElementType.CONSTRUCTOR:构造函数
    • ElementType.LOCAL_VARIABLE:局部变量
    • ElementType.ANNOTATION_TYPE:注解
    • ElementType.PACKAGE:包
  • @Retention
    • RetentionPolicy.SOURCE:这种类型的Annotations只在源代码级别保留,编译时就会被忽略
    • RetentionPolicy.CLASS —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略
    • RetentionPolicy.RUNTIME —— 这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用.

2、注解的实现

@Service
public class MyInterceptor implements HandlerInterceptor{
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Test test = method.getAnnotation(Test.class);
            if(test!=null) {
    			System.out.println("@Test注解生效");
            }
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}

注意:以下代码为判断方法是否有@Test注解。因为是用拦截器实现的,所以当请求方法时,都会先进入拦截器,所以要进行判断。

if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Test test = method.getAnnotation(Test.class);
            if(test!=null) {
    			System.out.println("@Test注解生效");
 	    }
}

3、配置springboot拦截器

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
       @Autowired
    private MyInterceptor myInterceptor;
    /**
     * 配置注解拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor)
                .addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}

4、添加@Test注解

@Validated
@RestController
@RequestMapping(value = "/user")
public class UserController {
    @Test
    @GetMapping(value = "/userinfos")
    public void getUser( HttpServletRequest request) {
        System.out.println("请求controller");
    }

这样一个简单的自定义注解就完成了。

猜你喜欢

转载自blog.csdn.net/nihaoa50/article/details/85244904