<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
配置类,开启AspectJ支持
@Configuration @EnableAspectJAutoProxy public class AopConfig { }
定义接口
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Action { String name(); }
方法
@Service public class DemoAnnotationService { @Action(name = "注解式拦截的add操作") public void add() { } }
方法
@Pointcut("@annotation(web.aop.Action)") public void annotationPointCut() { } @After("annotationPointCut()") public void after(JoinPoint joinPoint) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); Action action = method.getAnnotation(Action.class); System.out.println("注解式拦截 " + action.name()); }
测试类
@RunWith(SpringRunner.class) @SpringBootTest(classes = AopConfig.class) public class AopTests { @Autowired DemoAnnotationService demoAnnotationService; @Test public void testAop() throws Exception { demoAnnotationService.add(); } }