springboot整合aop按照例子本来很简单,但是过程中间有可能会有一个坑。
先来官方标准做法:
我的springboot用的版本是1.5.6.RELEASE。
在pom.xml中加入aop的依赖就可以了:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<scope>compile</scope>
</dependency>
然后就可以像标准的aop一样用了,这里贴一段例子:
@Aspect
@Component
public class CommonLog {
private static final Logger sysLogger = Logger.getLogger(StateDefine.SYS_LOG);
@Pointcut("execution(* org.redstarofsleep.aopsample..*Service.* (..))")
public void service(){};
/**
* Description: Service方法抛异常时自动记日志
* @param ex
*/
@AfterThrowing(pointcut="service()", throwing="ex")
public void exceptionOfMethod(JoinPoint joinPoint, Exception ex) {
// sysLogger.error(LogUtil.getExceptions(ex));
// sysLogger.error("*** Error service occurred: ", ex);
// 在日志中记录异常trace
sysLogger.error("### Error Service==========>>" + LogUtil.getInformation(joinPoint));
LogUtil.logExceptionTrace(ex);
}
}
本来到这里就可以结束了。但是这段代码编译并没有报错,一启动就报JointPoint这个类找不到。很少奇怪。
可能是这个版本整合的包有问题,这个版本的spring-boot-starter-aop整合的aspectjweaver版本是1.8.10,换成1.8.7问题就解决了,所以pom修改如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>