springboot3加密配置文件的值
实现方案:自定义加密配置处理器
1.新增一个自定义处理器的类
@Component
public class EncryptedPropertyProcessor implements EnvironmentPostProcessor {public static final String NACOS_DECRYPT_SECRET_KEY = "LgZOYR7vaBFzihJt";private static final String ENCRYPTED_PREFIX = "encrypted:";@Overridepublic void postProcessEnvironment(ConfigurableEnvironment environment,SpringApplication application) {Map<String, Object> decryptedProperties = new HashMap<>();for (PropertySource<?> propertySource : environment.getPropertySources()) {if (propertySource instanceof EnumerablePropertySource) {processPropertySource((EnumerablePropertySource<?>) propertySource, decryptedProperties);}}if (!decryptedProperties.isEmpty()) {environment.getPropertySources().addFirst(new MapPropertySource("decryptedProperties", decryptedProperties));}}private void processPropertySource(EnumerablePropertySource<?> propertySource,Map<String, Object> decryptedProperties) {for (String propertyName : propertySource.getPropertyNames()) {Object value = propertySource.getProperty(propertyName);if (value instanceof String && ((String) value).startsWith(ENCRYPTED_PREFIX)) {String encryptedValue = ((String) value).substring(ENCRYPTED_PREFIX.length());try {String decryptValue = new String(Aes.decrypt(Aes.hexString2Bytes(encryptedValue), NACOS_DECRYPT_SECRET_KEY), "utf-8");decryptedProperties.put(propertyName, decryptValue);} catch (Exception e) {throw new RuntimeException("Failed to decrypt property: " + propertyName, e);}}}}
加解密方式可自行封住方法,比较灵活
2. 注册处理器
在 src/main/resources/META-INF/spring.factories
中添加:
org.springframework.boot.env.EnvironmentPostProcessor=com.yourpackage.EncryptedPropertyProcessor
重启项目后会根据处理器类覆盖解密后的yml配置的值