注解拦截aop

spring boot 项目添加aop依赖

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

猜你喜欢

转载自xl822786603.iteye.com/blog/2334626