背景
照着这篇文章Springboot敏感字段脱敏敲了一下例子,然后有一些需要注意的地方,这里记录一下。
代码
首先是需要引入的依赖项,如下:
implementation 'org.assertj:assertj-core:3.21.0' implementation 'org.springframework:spring-aspects:5.3.13' implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.4' implementation 'com.alibaba:fastjson:1.2.78' implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0' testImplementation 'org.springframework.boot:spring-boot-starter-test' implementation 'org.springframework:spring-aop:5.3.14'
配置文件里还需要配置一下:
jasypt.encryptor.password: 71144850f4fb4cc55fc0ee6935badddf
然后其他代码看原博客就可以。
改进
这里主要写一下,改动了的地方,也就是EncryptHandler的handler方法,因为这个handler方法这能处理参数或者返回值为具体对象,也就是UserVo
的情况,处理不了List<UserVo>
的情况,下面直接上上代码:
private Object handler(Object obj, EncryptConstant type) throws IllegalAccessException { if (Objects.isNull(obj)) { return null; } //判断是否是list Class cls2 = obj.getClass(); if (cls2.isAssignableFrom(ArrayList.class) ||cls2.isAssignableFrom(List.class) ||cls2.isAssignableFrom(LinkedList.class)){ List<Object> list= (List<Object>) obj; list.forEach(object->{ try { processObj(object,type); } catch (IllegalAccessException e) { e.printStackTrace(); } }); }else { processObj(obj,type); } return obj; } private void processObj(Object obj, EncryptConstant type) throws IllegalAccessException { Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { boolean hasSecureField = field.isAnnotationPresent(EncryptField.class); if (hasSecureField) { field.setAccessible(true); String realValue = (String) field.get(obj); String value; if (DECRYPT.equals(type)) { value = stringEncryptor.decrypt(realValue); } else { value = stringEncryptor.encrypt(realValue); } field.set(obj, value); } } }