自定義注解 引數判空(注解+AOP)
(AOP相關依賴需要在pom檔案中自行匯入)
一、創建自定義注解 CheckNull
1、新建 @interface 檔案 checkNull (可以先創建.java檔案后將class檔案改成@interface即可)
2、關于@Retention、@Documented、@Target詳情去看 元注解, 傳送門:https://blog.csdn.net/liang100k/article/details/79515910
package org.jeecg.modules.portal.anno;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target({ElementType.METHOD, ElementType.TYPE,ElementType.PARAMETER})
public @interface CheckNull {
}
二、創建切面(AOP)
1、加上@Aspect
2、定義切點@Pointcut(”@annotation(注解路徑)“)
? @annotation可以理解為切點在一個注解上
? @Before 前置增強
? @Around 環繞增強
? @after 后置增強
? 具體去看相關文章:https://blog.csdn.net/zhanglf02/article/details/78132304
3.在環繞增強中寫判空的邏輯( Result 為自己封裝的統一回傳結果,也可以直接拋出一個例外)
附原始碼:
package org.jeecg.modules.portal.aop;
import cn.hutool.core.util.StrUtil;
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.aspectj.lang.reflect.MethodSignature;
import org.jeecg.common.api.vo.Result;
import org.springframework.stereotype.Component;
@Aspect
@Component
@SuppressWarnings({"unused"})
public class MyAspect {
@Pointcut("@annotation(org.jeecg.modules.portal.anno.CheckNull)") //自定義切點-->(作用于哪里)
public void annotationPointcut() {
}
@Before("annotationPointcut()") //進入方法前的操作
public void before(JoinPoint joinPoint) {
}
@Around("annotationPointcut()")
public Object round(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String[] params = signature.getParameterNames();//獲取所有的引數名稱
Object[] args = joinPoint.getArgs();//獲取所有的引數值
int length = args.length;
for (int i = 0; i <length ; i++) {
String s = args[i].toString();
if(StrUtil.isEmpty(s)){
String msg = "引數"+params[i]+"不能為空";
return Result.error(msg);
}
}
return joinPoint.proceed();
}
}
三、實體測驗
1、在控制器上加上創建好的注解 @CheckNull
/**
* 測驗用的介面
*
*/
@ApiOperation(value="測驗介面", notes="測驗介面")
@PutMapping(value = "/testA")
@CheckNull
public Result<String> testA(@RequestParam(name = "a",required = false) String a,
@RequestParam(name = "b",required = false)String b) {
return Result.OK("");
}
測驗結果:

小白,, 功能還待完善,,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/245657.html
標籤:java
上一篇:上班無聊 ,手敲九九乘法表!
