AOP實現參數的判空問題

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

 

1. NullDisable註解spring

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

 

2. ParamExceptionapp

public class ParamException extends RuntimeException{

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

 

3. ValidParameterpost

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測試spa

相關文章
相關標籤/搜索