1.引用Aspectj包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
2.spring xml添加配置
<aop:aspectj-autoproxy proxy-target-class="true"/>
proxy-target-class=true优先用cglib,aop会自动切换
3.定义切面
@Component
@Aspect
public class AspectLogger {
}
4.定义PointCut
/**
*多种方式定义PointCut的value
* 1、execution(* com.xyz.service.AccountService.*(..)) AccountService 接口的任意方法的执行
* 2、this(com.test.spring.aop.pointcutexp.Intf) 实现了Intf接口的所有类,如果Intf不是接口,限定Intf单个类.
* 3、within(com.test.spring.aop.pointcutexp.*) pointcutexp包里的任意类.
* 4、@target()
* 5、@within()
* 6、@annotation
* (@within和@target针对类的注解,@annotation是针对方法的注解)
*/
//例子中用的是注解
@Pointcut("@annotation(com.xxx.LoggerAnnotation)")
public void pvAspect() {
}
5、定义行为
@Component
@Aspect
public class AspectLogger {
private static final Logger LOGGER = LoggerFactory.getLogger(AspectLogger.class);
//数据流出切点
@Pointcut("@annotation(com.xxx.LoggerAnnotation)")
public void pvAspect() {
}
//@Before、@Around、@After、@AfterReturning、@AfterThrowing
@Around("pvAspect()")
public Object rpcLog(ProceedingJoinPoint joinPoint) throws Throwable {
//方法体
}
}