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_www.thd178.com/ 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)www.dfgjpt.com/ {
HandlerMethod handlerMethod =www.ysyl157.com   (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
Test test = method.getAnnotation(Test.class);
if(test!=null) {
System.out.println("9999999999999");
}
}
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView)www.dasheng178.com  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

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

你可能感兴趣的:(springboot 实现自定义注解)