涉及关键词:pointcut execution
适用范围:SpringMVC springboot
常用execution 表达式写法整理(持续更新中)
任意公共方法的执行:
execution(public * *(..))
##public可以省略, 第一个* 代表方法的任意返回值 第二个参数代表任意包+类+方法 (..)任意参数
任何一个以“set”开始的方法的执行:
execution(* set*(..))
UserService接口的任意方法:
execution(* com.coffee.service.UserService.*(..))
定义在com.coffee.service包里的任意方法的执行:
execution(* com.coffee.service.*.*(..))
#第一个 .* 代表任意类, 第二个 .* 代表人以方法
定义在service包和所有子包里的任意类的任意方法的执行:
execution(* com.coffee.service..*.*(..))
# ..* 代表任意包或者子包
定义在com.coffee包和所有子包里的UserService类的任意方法的执行:
execution(* com.coffee..UserService.*(..))")
配置多个表达式时如何求并集/交集
关键词:或
使用 ||
, or
关键词:与
使用 &&
, and
关键词:非
使用 !
示例代码:
// 代码片段 可用
@Aspect
@Component
public class AopController {
private static final Logger logger = LoggerFactory.getLogger(AopController.class);
ThreadLocal<ResultBean> resultBeanThreadLocal = new ThreadLocal<>();
ThreadLocal<PageResultBean<?>> pageResultBeanThreadLocal = new ThreadLocal<>();
ThreadLocal<Long> start = new ThreadLocal<>();
@Pointcut(value = "execution(public com.example.beans.ResultBean *(..)))")
public void handlerResultBeanMethod() {
}
/**
* 定义一个切点
*/
@Pointcut(value = "execution(public com.example.beans.PageResultBean *(..)))")
public void handlerPageResultBeanMethod() {
}
@Around("handlerPageResultBeanMethod()")
public Object handlerPageResultBeanMethod(ProceedingJoinPoint pjp) {
start.set(System.currentTimeMillis());
try {
pageResultBeanThreadLocal.set((PageResultBean<?>)pjp.proceed());
logger.info(pjp.getSignature() + " 方法执行耗时:" + (System.currentTimeMillis() - start.get()));
} catch (Throwable e) {
ResultBean<?> resultBean = handlerException(pjp , e);
pageResultBeanThreadLocal.set(new PageResultBean<>().setMsg(resultBean.getMsg()).setCode(resultBean.getCode()));
}
return pageResultBeanThreadLocal.get();
}
@Around("handlerResultBeanMethod()")
public Object handlerResultBeanMethod(ProceedingJoinPoint pjp) {
start.set(System.currentTimeMillis());
try {
resultBeanThreadLocal.set((ResultBean<?>)pjp.proceed());
logger.info(pjp.getSignature() + " 方法执行耗时:" + (System.currentTimeMillis() - start.get()));
} catch (Throwable e) {
resultBeanThreadLocal.set(handlerException(pjp , e));
}
return resultBeanThreadLocal.get();
}
/**
* 封装异常信息,注意区分已知异常(自己抛出的)和未知异常
*/
private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
ResultBean<?> result = new PageResultBean();
logger.error(pjp.getSignature() + " error ", e);
// 已知异常
if (e instanceof CheckException) {
result.setMsg(e.getLocalizedMessage());
result.setCode(ResultBean.FAIL);
} else if (e instanceof UnloginException) {
result.setMsg("Unlogin");
result.setCode(ResultBean.NO_LOGIN);
} else {
result.setMsg(e.toString());
result.setCode(ResultBean.FAIL);
}
return result;
}
}