springboot aop方式實(shí)現(xiàn)接口入?yún)⑿r?yàn)的示例代碼
一、前言
在實(shí)際開發(fā)項(xiàng)目中,我們常常需要對(duì)接口入?yún)⑦M(jìn)行校驗(yàn),如果直接在業(yè)務(wù)代碼中進(jìn)行校驗(yàn),則會(huì)顯得代碼非常冗余,也不夠優(yōu)雅,那么我們可以使用aop的方式校驗(yàn),這樣則會(huì)顯得更優(yōu)雅。
二、如何實(shí)現(xiàn)?
1.添加maven依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>2.定義一個(gè)工具類ValidationUtil
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class ValidationUtil {
private static ValidationUtil util;
private Validator validator;
public ValidationUtil() {
// TODO Auto-generated constructor stub
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
this.validator = factory.getValidator();
}
/**
* @return the validator
*/
public Validator getValidator() {
return validator;
}
public static ValidationUtil getValidationUtil() {
if (util == null) {
util = new ValidationUtil();
}
return util;
}
public static List<CheckErrorResultDto> validate(Object o) {
Set<ConstraintViolation<Object>> set = ValidationUtil
.getValidationUtil().getValidator().validate(o);
List<CheckErrorResultDto> errorList = null;
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
for (ConstraintViolation<Object> cv : set) {
if (errorList == null) {
errorList = new ArrayList<CheckErrorResultDto>();
}
String message = MessageResolver.getMessage(request,
cv.getMessage());
errorList.add(new CheckErrorResultDto(cv.getPropertyPath()
.toString(), message));
}
return errorList;
}
public static List<CheckErrorResultDto> validate(Object o,Class<?> ...c) {
Set<ConstraintViolation<Object>> set = ValidationUtil
.getValidationUtil().getValidator().validate(o,c);
List<CheckErrorResultDto> errorList = null;
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
for (ConstraintViolation<Object> cv : set) {
if (errorList == null) {
errorList = new ArrayList<CheckErrorResultDto>();
}
String message = MessageResolver.getMessage(request,
cv.getMessage());
errorList.add(new CheckErrorResultDto(cv.getPropertyPath()
.toString(), message));
}
return errorList;
}3.校驗(yàn)錯(cuò)誤信息實(shí)體類。
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class CheckErrorResultDto {
private String fieldName;
private String msg;
}4.編寫校驗(yàn)AOP
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
@Order(1)
@Aspect
@Component
@EnableAspectJAutoProxy(exposeProxy=true)
public class ValidAop {
/**
* 校驗(yàn)傳入實(shí)體
*
* @param pjp
* @throws Throwable
*/
@Around("@annotation(com.smartcitysz.dp.dataasset.aop.annotation.Valid)")
public Object aroundExec(ProceedingJoinPoint pjp) throws Throwable {
MethodSignature ms = (MethodSignature) pjp.getSignature();
Method method = ms.getMethod();
Valid annotation = method.getAnnotation(Valid.class);
if (annotation != null) {
List<CheckErrorResultDto> errorList=new ArrayList<CheckErrorResultDto>();
Object[] args=pjp.getArgs();
Class<?>[] checkToken = annotation.value();
Class<?>[] group = annotation.group();
for (Class c : checkToken) {
for (Object obj : args) {
if (c == obj.getClass()) {
List<CheckErrorResultDto> result=null;
if(group.length<1){
result= ValidationUtil.validate(obj);
}else{
result= ValidationUtil.validate(obj,group);
}
if(result!=null)
errorList.addAll(result);
}
}
}
if(errorList.size()>0){
ResponseData vo=new ResponseData();
vo.setCode(ApiCodeEnum.ILLEGAL_PARAMETER.getCode());
vo.setMsg(ApiCodeEnum.ILLEGAL_PARAMETER.getMsg());
vo.setData(errorList);
return vo;
}
}
return pjp.proceed();
}
}5.定義一個(gè)校驗(yàn)注解Valid
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Valid {
Class<?>[] value() default {};
Class<?>[] group() default {};
}6.最后在Controller定義的接口上加上注解指定要校驗(yàn)的對(duì)象即可。
到此這篇關(guān)于springboot aop方式實(shí)現(xiàn)接口入?yún)⑿r?yàn)的示例代碼的文章就介紹到這了,更多相關(guān)springboot aop接口入?yún)⑿r?yàn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實(shí)現(xiàn)移動(dòng)指定圖片到指定目錄
這篇文章主要為大家詳細(xì)介紹了如何使用Python的os和shutil庫實(shí)現(xiàn)自動(dòng)化查找和移動(dòng)圖片功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下2025-02-02
Python使用XPath實(shí)現(xiàn)動(dòng)態(tài)屬性的精準(zhǔn)定位
在Web自動(dòng)化測(cè)試和數(shù)據(jù)爬取過程中,動(dòng)態(tài)生成的元素屬性常常讓定位工作變得棘手,本文將深入探討如何使用XPath的強(qiáng)大功能,結(jié)合Python實(shí)現(xiàn)動(dòng)態(tài)屬性的精準(zhǔn)定位,提供可復(fù)用的解決方案和實(shí)戰(zhàn)案例,有需要的可以了解下2026-04-04
Python設(shè)計(jì)模式之迭代器模式原理與用法實(shí)例分析
這篇文章主要介紹了Python設(shè)計(jì)模式之迭代器模式原理與用法,結(jié)合具體實(shí)例形式分析了迭代器模式的概念、原理、定義及使用方法,代碼注釋說明簡(jiǎn)單易懂,需要的朋友可以參考下2019-01-01
python實(shí)現(xiàn)單線程多任務(wù)非阻塞TCP服務(wù)端
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)單線程多任務(wù)非阻塞TCP服務(wù)端的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
使用Python實(shí)現(xiàn)Exce格式化批處理工具
原始Excel數(shù)據(jù)常常存在格式不統(tǒng)一、空值、重復(fù)數(shù)據(jù)等問題,影響數(shù)據(jù)的準(zhǔn)確性和可用性,所以本文就來使用Python編寫一個(gè)Excel數(shù)據(jù)清洗工具,有需要的小伙伴可以參考一下2025-04-04
python pandas dataframe 按列或者按行合并的方法
下面小編就為大家分享一篇python pandas dataframe 按列或者按行合并的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-04-04

