1. 程式人生 > >springboot 實現自定義註解

springboot 實現自定義註解

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");
    }

這樣一個簡單的自定義註解就完成了。