AOP 無感校驗

好mingzi给猪了發表於2024-04-17
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Scope("protoptype")
public class Result {
     
     private Result r;
     
     @Pointcut("execution(* com.ceair.unified.ws.*..*.*(..))")
     private void log() {
     }
     
     @Before("log() && args(t))") // T建議是map或者json型別,只要原始型別裡有get()方法且有一個入參可以適配所有型別。
     public <T> void before(JoinPoint joinPoint,T t) {
             try{
                 //需要校驗的屬性
                 String arr [] = new String []{"org","channel","name","container","signNum"};
                for(String s : arr){
                    //獲得T類中的get()方法
                    Method m = t.getClass().getMethod("get", Object.class);
                    //呼叫t類中的get()方法,傳入引數s
                    if(m.invoke(t, s) == null || m.invoke(t, s) == ""){
                        r =  Result.error(s+":不能為空");
                    }
                }
            }catch(Exception e){
                r = Result.error("unkonw exception");
            }
            r =  Result.ok();
     }
     
     @Around("log()")  
     public Object around(ProceedingJoinPoint pjp) throws Throwable{
        Object obj = null;
         if(r.getCode().equals(200)){
            obj = pjp.proceed();//呼叫業務...
        }else{
            //直接返回撥用方,不會進入業務
            return r;
        }
         /**
          * 業務執行完....
          * 返回撥用方
          * */
        return obj;
     }
     
     private Integer code;
    private String message;
    public static Result error(String message){
        Result r = new Result();
        r.setCode(-100);
        r.setMessage(message);
        return r;
    }
    
    public static Result ok(){
        Result r = new Result();
        r.setCode(200);
        return r;
    }
    
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

裝飾著模式:不改變原有業務程式碼邏輯 增加功能。

Are you ok ?

相關文章