AspectJ获取Annotation的属性值

效果java

xml开启AOP配置apache

<aop:config proxy-target-class="false" />
<aop:aspectj-autoproxy />
<bean id="opLogAspectj" class="com.noob.aspectj.OpLogAspectj"></bean>

使用方式:ui

@OpLog(model = 99)
public String test() {// do somethings }

@RequiresPermissions("rule:delete")
public Response<Integer> delete(String params, HttpServletRequest request) { // do somethings }

aspectj实现:spa

package com.noob.aspectj;

import lombok.extern.slf4j.Slf4j;
​
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface OpLog {
	int model() default 1;
}
  1. 对带指定注解切入,并获取到注解的属性值
    (若advice方法含注解对象,“@annotation(参数名)” 是必须的,argNames 配置非必要!但二者配置的值必定要与advice方法内注解对象名一致! 不然没法匹配参数,启动报错)
    //表达式
        @Pointcut(value = "@annotation(com.noob.annotation.OpLog)")
        //签名
        public void opLogPointcut(){}
        
        // 另外的写法  @Around(value = "execution(@cn.utrust.trusts.config.OpLog * *.*(..)) && @annotation(opLog)"  , argNames="opLog") 
        @Around(value= "opLogPointcut() && @annotation(opLog)" ) 
        public Object aroundLog(ProceedingJoinPoint point, OpLog opLog) throws Throwable{
            Object obj = null;
            Object[] args = point.getArgs();
            
            try {
                obj = point.proceed(args);
            } catch (Throwable e) {
                log.error("方法执行异常", e);
            }
            long endTime = System.currentTimeMillis();
            MethodSignature signature = (MethodSignature) point.getSignature();
            String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
            return obj;
        }
  2. 指定位置的参数
    (args配置值内的参数名必定要与advice方法内参数名一致, 执行时会匹配指定位置上参数类型一致的链接点进入切面)
    @Aspect
    @Slf4j
    public class OpLogAspectj {
       
     @Pointcut(value = "@annotation(org.apache.shiro.authz.annotation.RequiresPermissions)")  
     public void permissionPointcut(){}
    
      @Around(value= "permissionPointcut() && (args(request, ..) || args(.., request))")
      public Object aroundPermission(ProceedingJoinPoint point, HttpServletRequest request) throws Throwable{
            Object obj = null;
            Object[] args = point.getArgs();
            
            try {
                SsoUser ssoUser = SsoSession.getCurrentUser(request);
                obj = point.proceed(args);
            } catch (Throwable e) {
                log.error("方法执行异常", e);
            }
            return obj;
        }    
    }
     
相关文章
相关标签/搜索