<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
configuration class to enable AspectJ support
@Configuration @EnableAspectJAutoProxy public class AopConfig { }
define interface
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Action { String name(); }
method
@Service public class DemoAnnotationService { @Action(name = "Add operation of annotation interception") public void add() { } }
method
@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("Annotated interception" + action.name()); }
test class
@RunWith(SpringRunner.class) @SpringBootTest(classes = AopConfig.class) public class AopTests { @Autowired DemoAnnotationService demoAnnotationService; @Test public void testAop() throws Exception { demoAnnotationService.add (); } }