1.场景:假如我要拦截有些url请求,但是没有规定在哪个包哪个类下,这时就可用自定义注解+aop拦截。
2.使用-自定义注解:
a.首先创建一个自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Auth {
}
b.写AOP类
@Aspect
@Component
public class AuthImpl {
@Before("@annotation(com.cn.annotation.Auth)")
public void doBefore() throws Exception{
System.out.println("拦截到了!");
}
}
c.在需要拦截的请求加上自定义的注解
@RestController
public class TestConterller {
@Auth
@RequestMapping("/hello")
public String hello() {
System.out.println("Controller==============");
return "hello";
}
}
3.测试
请求url:http://localhost:8090/hello
查看日志: