一、非注解形式
1、启动类加入注解
@EnableAspectJAutoProxy
2、定义切面
@Aspect
@Component
public class InterWebLogAspect {
@Pointcut("execution(* cn.egenie.mall.inter.api.controller..*.*(..))") //作用域
public void executionService() {
}
@Around("executionService()")
public Object around(ProceedingJoinPoint jp) throws Throwable {
LOGGER.debug("进入日志环绕通知");
//记录日志业务代码
try {
//StopWatch 计时
StopWatch clock = new StopWatch();
clock.start();
result = jp.proceed();
clock.stop();
//调用方式耗时
long executeTime = clock.getTime();
} catch (Exception e) {
result = "服务异常"
}
return result;
}
}
注解形式
1、启动类加入注解
@EnableAspectJAutoProxy
2、创建注解
@Inherited
@Documented
@Target({ElementType.FIELD, ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AccessLimit {
// 可定义注解默认参数
}
3、定义切面
@Aspect
@Component
public class InterWebLogAspect {
@Pointcut("execution(*cn.egenie.mall.inter.annotation..*.*(..))") //作用域换成注解拦截
public void executionService() {
}
@Around("executionService()")
public Object around(ProceedingJoinPoint jp) throws Throwable {
LOGGER.debug("进入日志环绕通知");
//记录日志业务代码
try {
//StopWatch 计时
StopWatch clock = new StopWatch();
clock.start();
result = jp.proceed();
clock.stop();
//调用方式耗时
long executeTime = clock.getTime();
} catch (Exception e) {
result = "服务异常"
}
return result;
}
}
4、控制器加上注解
@AccessLimit
@RequestMapping(value = "/test", method = RequestMethod.POST)
public void test(){
//业务代码
}