AOP實現參數的判空問題


不想每次都去判斷必傳的參數是否為空,寫代碼太繁瑣了,正好最近用了AOP實現權限控制,依葫蘆畫瓢,現在用它實現參數的判空,至於AOP的原理之類,自己百度了解一下吧

 

1. NullDisable注解

@Documented
@Retention(RUNTIME)
@Target({ TYPE, METHOD, PARAMETER })
public @interface NullDisable {
    
}

 

2. ParamException

public class ParamException extends RuntimeException{

    private static final long serialVersionUID = -4993447045204262508L;
    
    public ParamException(){
        super("參數不能為空");
    }
    
    public ParamException(String message){
        super(message);
    }
}

 

3. ValidParameter

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.test.exception.ParamException;

@Aspect
@Component
public class ValidParameter {
    //com.test.controller包下所有的類
    @Pointcut("execution(* com.test.controller..*.*(..)))")
    public void valid() {};
    
    @Around("valid()")
    public Object check(ProceedingJoinPoint joinPoint) throws Exception{
        
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //獲得參數類型
        final Parameter[] parameters = method.getParameters();
        //參數值
        final Object[] args = joinPoint.getArgs();
        //參數名稱
        String[] names = signature.getParameterNames();
        
        
        for(int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            Object annotation = parameter.getAnnotation(NullDisable.class);
            //含有不為空的注解的參數
            if (null != annotation) {
                if (null == args[i]) {
                    throw new ParamException(String.format("參數:%s,不能為空", names[i]));
                }
            }
            
        }
    return joinPoint.proceed(); } }

 

2. controller

    @GetMapping("test")
    @PermissionSetter
    public Object test(
            @RequestParam(value = "name") String name,
            @NullDisable @RequestParam(value = "date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date
            ){
        return "";
    }

postman測試

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM