下面列出了怎么用org.aspectj.lang.annotation.Around的API类实例代码及写法,或者点击链接到github查看源代码。
@Around("@annotation(com.jd.laf.web.vertx.annotation.Path)")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = joinPoint.proceed();
if (result instanceof Response) {
Response response = (Response) result;
Class<?> clazz = joinPoint.getSignature().getDeclaringType();
if (response.getCode() == 200 && !exceptCommandClasses.contains(clazz)) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Path path = methodSignature.getMethod().getAnnotation(Path.class);
int operType = -1;
if (StringUtils.containsIgnoreCase(path.value(), "add")) {
operType = OperLog.OperType.ADD.value();
} else if (StringUtils.containsIgnoreCase(path.value(), "delete")) {
operType = OperLog.OperType.DELETE.value();
} else if (StringUtils.containsIgnoreCase(path.value(), "update")) {
operType = OperLog.OperType.UPDATE.value();
}
if (operType >= 1 && operType <= 3) {
addOperLog(clazz.getSimpleName(), path.value(), joinPoint.getArgs(), operType);
}
}
}
return result;
}
@Around("BindingResult()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs();
for (Object arg : args) {
if (arg instanceof BindingResult) {
BindingResult result = (BindingResult) arg;
if (result.hasErrors()) {
FieldError fieldError = result.getFieldError();
if(fieldError!=null){
return CommonResult.validateFailed(fieldError.getDefaultMessage());
}else{
return CommonResult.validateFailed();
}
}
}
}
return joinPoint.proceed();
}
@Around("dsPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable
{
DataSource dataSource = getDataSource(point);
if (StringUtils.isNotNull(dataSource))
{
DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
}
try
{
return point.proceed();
}
finally
{
// 销毁数据源 在执行方法之后
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
@Around("retryOnOptFailure()")
@Transactional(rollbackFor = Exception.class)
public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
int numAttempts = 0;
do {
numAttempts++;
try {
//再次执行业务代码
return pjp.proceed();
} catch (TryAgainException ex) {
if (numAttempts > maxRetries) {
//log failure information, and throw exception
// 如果大于 默认的重试机制 次数,我们这回就真正的抛出去了
throw new ApiException(ApiResultEnum.ERROR);
}else{
//如果 没达到最大的重试次数,将再次执行
System.out.println("=====正在重试====="+numAttempts+"次");
}
}
} while (numAttempts <= this.maxRetries);
return null;
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
long nowMillis = System.currentTimeMillis();
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
Object[] parameters = joinPoint.getArgs();
String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
Object resObject;
try {
resObject = joinPoint.proceed(parameters);
} catch (Exception e) {
logger.error("aspect error req ip:{}|class_method:{}|args:{}", getIpAddr(request), classMethod, Arrays.toString(parameters));
throw e;
}
logger.info("aspect req ip:{}|class_method:{}|args:{},response:{},cost time:{}ms", getIpAddr(request), classMethod,
Arrays.toString(parameters), resObject, System.currentTimeMillis() - nowMillis);
return resObject;
}
@Around("@annotation(Idempotent)")
public Object around(ProceedingJoinPoint point) throws Throwable {
Method method = ((MethodSignature) point.getSignature()).getMethod();
Idempotent shelter = method.getAnnotation(Idempotent.class);
String name = shelter.name();
Object[] args = point.getArgs();
HttpServletRequest request = (HttpServletRequest) args[0];
PointOpParam param = (PointOpParam) args[1];
BaseResponse res;
// String seq = request.getParameter(HyenaConstants.REQ_IDEMPOTENT_SEQ_KEY);
String seq = param.getSeq();
request.setAttribute(HyenaConstants.REQ_IDEMPOTENT_SEQ_KEY, seq);
res = this.preProceed(name, param, method);
if (res != null) {
return res;
}
res = (BaseResponse) point.proceed(point.getArgs());
this.postProceed(name, param, res);
return res;
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice.
* @return result.
* @throws Throwable throws {@link IllegalArgumentException}.
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if (log.isDebugEnabled()) {
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
@Around("execution(* org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.authorize(..))")
public Object doAroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs();
Map<String, String> parameters = (Map<String, String>) args[1];
Principal principal = (Principal) args[3];
if (principal instanceof TenantUsernamePasswordAuthenticationToken) {
TenantUsernamePasswordAuthenticationToken tenantToken = (TenantUsernamePasswordAuthenticationToken)principal;
String clientId = tenantToken.getClientId();
String requestClientId = parameters.get(OAuth2Utils.CLIENT_ID);
//判断是否不同租户单点登录
if (!requestClientId.equals(clientId)) {
try {
TenantContextHolder.setTenant(requestClientId);
//重新查询对应该租户的角色等信息
LoginAppUser user = userService.findByUsername(tenantToken.getName());
tenantToken = new TenantUsernamePasswordAuthenticationToken(user, tenantToken.getCredentials(), user.getAuthorities(), requestClientId);
args[3] = tenantToken;
} finally {
TenantContextHolder.clear();
}
}
}
return joinPoint.proceed(args);
}
@Around("BindingResult()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs();
for (Object arg : args) {
if (arg instanceof BindingResult) {
BindingResult result = (BindingResult) arg;
if (result.hasErrors()) {
FieldError fieldError = result.getFieldError();
if(fieldError!=null){
return CommonResult.validateFailed(fieldError.getDefaultMessage());
}else{
return CommonResult.validateFailed();
}
}
}
}
return joinPoint.proceed();
}
/**
* 执行核心方法
* 1. 判断是否拥有 {@link RetryAble} 标识的注解。
* 2. 没有则正常执行。
* @param point 切点
* @return 结果
* @throws Throwable 异常信息
*/
@Around("myPointcut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
final Method method = getCurrentMethod(point);
final RetryMethodHandler retryMethodHandler = InstanceFactory.getInstance()
.singleton(RetryMethodHandler.class);
//1. 判断注解信息
Optional<RetryAbleBean> retryAbleAnnotationOpt = retryMethodHandler.retryAbleAnnotation(method);
if(!retryAbleAnnotationOpt.isPresent()) {
return point.proceed();
}
//2. 重试执行
final Callable callable = buildCallable(point);
final RetryAbleBean retryAbleBean = retryAbleAnnotationOpt.get();
return retryMethodHandler.retryCall(retryAbleBean, callable);
}
@Around("servicePointcut()")
public Object doServiceAround(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
Signature signature = thisJoinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
final Method targetMethod = methodSignature.getMethod();
OptimisticLock optimisticLock = targetMethod.getAnnotation(OptimisticLock.class);
if (optimisticLock == null) {
throw new RuntimeException("乐观锁aop异常");
}
Class<? extends Exception>[] catchTypes = optimisticLock.catchType();
if (catchTypes == null || catchTypes.length == 0) {
throw new RuntimeException("乐观锁aop异常");
}
int retry = optimisticLock.retry();
Object object = tryServiceProceed(thisJoinPoint, catchTypes, retry);
return object;
}
@Around("excudeService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();
String url = request.getRequestURL().toString();
String method = request.getMethod();
String uri = request.getRequestURI();
String queryString = request.getQueryString();
logger.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);
// result的值就是被拦截方法的返回值
Object result = pjp.proceed();
logger.info("请求结束,controller的返回值是 " + result);
return result;
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice
* @return result
* @throws Throwable throws IllegalArgumentException
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if (log.isDebugEnabled()) {
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
@Around("logTime()")
public Object timeAround(ProceedingJoinPoint joinPoint) {
// 定义返回对象、得到方法需要的参数
Object obj = null;
Object[] args = joinPoint.getArgs();
long startTime = System.currentTimeMillis();
try {
obj = joinPoint.proceed(args);
} catch (Throwable e) {
e.printStackTrace();
log.error("统计某方法执行耗时环绕通知出错", e);
}
// 获取执行的方法名
long endTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
// 打印耗时的信息
log.info(String.format("「%s」执行时间为:%d ms",methodName, endTime - startTime));
return obj;
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice
* @return result
* @throws Throwable throws IllegalArgumentException
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if (log.isDebugEnabled()) {
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
@Around("execution(@org.apache.servicecomb.saga.omega.transaction.annotations.Compensable * *(..)) && @annotation(compensable)")
Object advise(ProceedingJoinPoint joinPoint, Compensable compensable) throws Throwable {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
String localTxId = context.localTxId();
context.newLocalTxId();
LOG.debug("Updated context {} for compensable method {} ", context, method.toString());
int retries = compensable.retries();
RecoveryPolicy recoveryPolicy = RecoveryPolicyFactory.getRecoveryPolicy(retries);
try {
return recoveryPolicy.apply(joinPoint, compensable, interceptor, context, localTxId, retries);
} catch (Exception e) {
throw e;
} finally {
context.setLocalTxId(localTxId);
LOG.debug("Restored context back to {}", context);
}
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice.
* @return result.
* @throws Throwable throws {@link IllegalArgumentException}.
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if (log.isDebugEnabled()) {
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice
* @return result
* @throws Throwable throws IllegalArgumentException
*/
@Around("loggingPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if (log.isDebugEnabled()) {
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice
* @return result
* @throws Throwable throws IllegalArgumentException
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if (log.isDebugEnabled()) {
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
@SuppressWarnings("unchecked")
@Around("syncSaveEsData()")
public Object syncSaveEsData(ProceedingJoinPoint pjp) throws Throwable{
Object[] args = pjp.getArgs() ;
if(args.length == 1){
Object data = args[0] ;
if(data!=null){
if(data instanceof UKeFuList){
/**只有一个地方用到,从DB同步数据到ES**/
}else if(data instanceof List){
List<Object> dataList = (List<Object>)data ;
for(Object dbData : dataList){
UKTools.multiupdate(new MultiUpdateEvent<Object>(dbData , dbDataRes, UKDataContext.MultiUpdateType.SAVE.toString()));
}
}else{
UKTools.multiupdate(new MultiUpdateEvent<Object>(data, dbDataRes, UKDataContext.MultiUpdateType.SAVE.toString()));
}
}
}
return pjp.proceed();
}
@Around("RetryPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
Method method = ((MethodSignature) point.getSignature()).getMethod();
Retry retry = method.getAnnotation(Retry.class);
for (int i = 0; i < retry.times(); i++) {
try {
if (i != 0) {
log.info("The {} times to retry {}", i + 1, method.getName());
}
return point.proceed();
} catch (IOException e) {
log.error("IOException: {}", e.getMessage());
Thread.sleep(retry.interval() * 1000);
}
}
throw new IOException();
}
@Around("excudeService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();
String url = request.getRequestURL().toString();
String method = request.getMethod();
String uri = request.getRequestURI();
String queryString = request.getQueryString();
logger.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);
// result的值就是被拦截方法的返回值
Object result = pjp.proceed();
logger.info("请求结束,controller的返回值是 " + result);
return result;
}
@Around("@annotation(operateLog)")
public Object around(ProceedingJoinPoint point, OperateLog operateLog) throws Throwable {
// 获取类名
String className = point.getTarget().getClass().getName();
// 获取方法
String methodName = point.getSignature().getName();
// 开始时间
long beginTime = System.currentTimeMillis();
// 执行方法
Object result = point.proceed();
// 执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
// 日志描述
String description = operateLog.value();
// 异步记录日志
LogEventPublisher.publishOperateLogEvent(methodName, className, description, time);
return result;
}
@Around("pointCut()")
public Object arround(ProceedingJoinPoint point) throws Throwable{
HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
PermissionData pd = method.getAnnotation(PermissionData.class);
String component = pd.pageComponent();
authDataHandler(request, component);
return point.proceed();
}
/**
* 配置环绕通知,使用在方法logPointcut()上注册的切入点
*
* @param joinPoint join point for advice
*/
@Around("logPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object result;
currentTime.set(System.currentTimeMillis());
result = joinPoint.proceed();
Log log = new Log("INFO", System.currentTimeMillis() - currentTime.get());
currentTime.remove();
HttpServletRequest request = SecurityUtils.getHttpServletRequest();
logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), joinPoint, log);
return result;
}
@Around("aopPoint()")
public Object doRouter(ProceedingJoinPoint jp) throws Throwable {
long begin = System.currentTimeMillis();
Method method = getMethod(jp);
try {
return jp.proceed();
} finally {
long end = System.currentTimeMillis();
logger.info("\nitstack middleware schedule method:{}.{} take time(m):{}", jp.getTarget().getClass().getSimpleName(), method.getName(), (end - begin));
}
}
/**
* 环绕通知
*/
@Around(value = "pointcut()")
public Object around(ProceedingJoinPoint pjp) {
//request对象
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
try {
//获取返回值
Object o = pjp.proceed();
//拦截返回值为ModelAndView即可
if("org.springframework.web.servlet.ModelAndView".equals(o.getClass().getName())){
/*
PC端ua:windows nt、macintosh
移动端ua:iphone、ipod、android
*/
String adapter;
String ua = request.getHeader("user-agent").toLowerCase();
if (ua.contains("iphone") || ua.contains("ipod") || ua.contains("android")) {
adapter = "mobile";
} else {
adapter = "computer";
}
log.info("PC端、手机端页面适配器:" + adapter);
//强势修改
ModelAndView modelAndView = (ModelAndView) o;
String viewName = modelAndView.getViewName();
modelAndView.setViewName(adapter + "/" + viewName);
o = modelAndView;
}
return o;
} catch (Throwable throwable) {
//返回统一错误页面
log.error(throwable.getMessage());
return new ModelAndView("common/error/500");
}
}
@Around("execution(* android.app.Activity.setContentView(..))")
public void getSetContentViewTime(ProceedingJoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
String name = signature.toShortString();
long time = System.currentTimeMillis();
try {
joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
LogUtils.i(name + " cost " + (System.currentTimeMillis() - time));
}
@SneakyThrows
@Around("@annotation(inner)")
public Object around(ProceedingJoinPoint point, Inner inner) {
String header = request.getHeader(SecurityConstants.FROM);
if (inner.value() && !StrUtil.equals(SecurityConstants.FROM_IN, header)) {
log.warn("访问接口 {} 没有权限", point.getSignature().getName());
throw new AccessDeniedException("Access is denied");
}
return point.proceed();
}
/**
* 参考了org.springframework.security.access.prepost.PrePostAdviceReactiveMethodInterceptor#invoke的写法
*
* @param point 切点
* @return obj
*/
@Around("@annotation(com.itmuch.lightsecurity.annotation.PreAuthorize) ")
public Object preAuth(ProceedingJoinPoint point) {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
if (method.isAnnotationPresent(PreAuthorize.class)) {
PreAuthorize preAuthorize = method.getAnnotation(PreAuthorize.class);
String expression = preAuthorize.value();
Mono<Boolean> mono = ReactiveSpringElCheckUtil.check(
new StandardEvaluationContext(reactivePreAuthorizeExpressionRoot),
expression)
.filter(t -> t)
.switchIfEmpty(Mono.defer(() -> Mono.error(new LightSecurityException("Access Denied."))));
Class<?> returnType = method.getReturnType();
if (Mono.class.isAssignableFrom(returnType)) {
return mono
.flatMap(
auth -> this.proceed(point)
);
}
if (Flux.class.isAssignableFrom(returnType)) {
return mono
.flatMapMany(
auth -> this.<Flux<?>>proceed(point)
);
}
return mono
.flatMapMany(auth -> Flux.from(
this.proceed(point))
);
}
return this.proceed(point);
}