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;
        }    
    }
     
相關文章
相關標籤/搜索