aop的maven依赖:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
//没用到XML配置文件,所以用的是此注解 @EnableAspectJAutoProxy,如果有xml:<aop:aspectj-autoproxy proxy-target-class=“true” expose-proxy=“true” />
//自定义注解使用
在controller或者service层切入,下图在serviceImpl切入
//定义日志注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ResApplyLog {
String value() default "";
}
//切面处理类:around(里面入参出参方法类都可以获取到)
@Aspect
@Component
public class ResApplyLogAspect {
private Logger logger = LoggerFactory.getLogger(ResApplyLogAspect.class);
@Pointcut("@annotation(com.hulk.paas.support.common.validator.annotation.ResApplyLog)")
public void applyLogPointCut() {
logger.info("start");
//切面,将操作保存到数据表中
}
@Around(value = "applyLogPointCut()")
public Object assertAround(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = pjp.proceed(); //执行目标方法
long excTime = System.currentTimeMillis() - startTime;
logger.info("执行时间:" + excTime + "毫秒");
saveLog(pjp, excTime, result);
return result;
}