業務邏輯:將前端傳來的參數字段中的小寫字母轉成大寫字母
實現邏輯:通過自定義注解實現轉換,在相關的字段上添加指定注解,實現轉換。
實現目標:
步驟一:自定義注解(具體方法我這里就不介紹了,百度一大堆),直接看代碼
... import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author wzj */ @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface RemoveSpaceAndToUpperCase { Class<?>[] groups() default {}; }
步驟二:通過切面前置通知(忽略我的切入點命名)、反射獲取變量對象屬性值,從而實現轉換
@Order(2) @Before("errorController()") public void removeSpaceAndToUpperCase(JoinPoint joinPoint) { Object[] args = joinPoint.getArgs(); for (Object arg : args) { if (Objects.isNull(arg) || "".equals(arg)) { return; } //獲取相關類的所以屬性(getFields()無法獲取private屬性的字段) Field[] fields = arg.getClass().getDeclaredFields(); for (Field field : fields) { //是否使用RemoveSpaceAndToUpperCase注解 if (field.isAnnotationPresent(RemoveSpaceAndToUpperCase.class)) { for (Annotation annotation : field.getDeclaredAnnotations()) { //是否是自定義的RemoveSpaceAndToUpperCase注解 if (annotation.annotationType().equals(RemoveSpaceAndToUpperCase.class)) { try { //不去檢查Java語言權限控制(如private) field.setAccessible(true); if (Objects.isNull(field.get(arg)) || "".equals(field.get(arg))) { return; } //實現方法 String str = StringUtil.removeSpaceAndToUpperCase(field.get(arg).toString()); field.set(arg, str); } catch (IllegalAccessException e) { log.error(DefaultConstant.ILLEGAL_ARGUMENT_BUSINESS_EXCEPTION.getMessage(), e); throw new CheckException(DefaultConstant.ILLEGAL_ARGUMENT_BUSINESS_EXCEPTION); } } } } } } }
步驟三:我寫的實現現僅支持這種傳參:
暫不支持這種傳參校驗:
JoinPoint詳解:https://blog.csdn.net/qq_15037231/article/details/80624064
Field反射詳解:http://www.51gjie.com/java/795.html