序
本文次要钻研一下 mybatis-plus 的 SafetyEncryptProcessor
SafetyEncryptProcessor
mybatis-plus-boot-starter/src/main/java/com/baomidou/mybatisplus/autoconfigure/SafetyEncryptProcessor.java
public class SafetyEncryptProcessor implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
/**
* 命令行中获取密钥
*/
String mpwKey = null;
for (PropertySource<?> ps : environment.getPropertySources()) {if (ps instanceof SimpleCommandLinePropertySource) {SimpleCommandLinePropertySource source = (SimpleCommandLinePropertySource) ps;
mpwKey = source.getProperty("mpw.key");
break;
}
}
/**
* 解决加密内容
*/
if (StringUtils.isNotBlank(mpwKey)) {HashMap<String, Object> map = new HashMap<>();
for (PropertySource<?> ps : environment.getPropertySources()) {if (ps instanceof OriginTrackedMapPropertySource) {OriginTrackedMapPropertySource source = (OriginTrackedMapPropertySource) ps;
for (String name : source.getPropertyNames()) {Object value = source.getProperty(name);
if (value instanceof String) {String str = (String) value;
if (str.startsWith("mpw:")) {map.put(name, AES.decrypt(str.substring(4), mpwKey));
}
}
}
}
}
// 将解密的数据放入环境变量,并处于第一优先级上
if (CollectionUtils.isNotEmpty(map)) {environment.getPropertySources().addFirst(new MapPropertySource("custom-encrypt", map));
}
}
}
}
SafetyEncryptProcessor 实现了 EnvironmentPostProcessor 接口,在 postProcessEnvironment 办法中先是找到 mpw.key,而后遍历所有 PropertySource 的所有属性,找到 mpw: 结尾的,而后进行解密并替换到密文,最初放在 environment 的第一个 PropertySource
spring.factories
mybatis-plus-boot-starter/src/main/resources/META-INF/spring.factories
# Auto Configure
org.springframework.boot.env.EnvironmentPostProcessor=\
com.baomidou.mybatisplus.autoconfigure.SafetyEncryptProcessor
小结
之前的文章聊聊 springboot 的 EnvironmentPostProcessor 提到 springboot 提供了 EnvironmentPostProcessor 接口,该接口有 postProcessEnvironment 办法,其中 envrionment 参数类型为 ConfigurableEnvironment,即利用能够通过实现这个接口进行 env 环境变量的操作。而 mybatis-plus 的 SafetyEncryptProcessor 正是一个实战的好例子。