可以在 BeanDefinitionRegistryPostProcessor 实现类中调用 PropertySourcesUtils 中的 resolvePlaceholders 方法,手动解析属性中的加密值。具体代码示例如下:
@Configuration public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
// Do nothing
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
StringEncryptor encryptor = new MyEncryptor(); // 自定义的加密类
StringPropertyValueResolver resolver = new StringPropertyValueResolver() {
@Override
protected String resolveStringValue(String strVal) throws BeansException {
if (strVal != null && strVal.startsWith("{cipher}")) {
String cipherText = strVal.substring("{cipher}".length());
return encryptor.decrypt(cipherText);
}
return strVal;
}
};
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new MapPropertySource("myProps", new HashMap<>()));
configurer.setPropertySources(propertySources);
configurer.setPlaceholderPrefix("$(");
configurer.setPlaceholderSuffix(")");
configurer.setIgnoreUnresolvablePlaceholders(true);
configurer.setValueSeparator(":");
configurer.setSystemPropertiesMode(PropertySourcesPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
configurer.setPropertyValues(new MutablePropertyValues())
configurer.setPropertiesPersister(new DefaultPropertiesPersister());
PropertySourcesUtils.addPlaceholders(propertySources, configurer);
ResolvableType resolvableType = ResolvableType.forClass(StringValueResolver.class);
registry.registerBeanDefinition("myResolver", BeanDefinitionBuilder.rootBeanDefinition(ResolverType.class)
.addConstructorArgValue(resolver)
.setFactoryMethod("resolvableAt", resolvableType)
.getBeanDefinition());
}
}
其中,MyEncryptor 是自定义的加密类,实现了 StringEncryptor 接口。调用 resolver 的 resolveStringValue 方法可以手动解析属性中的加密值,将其解密后返回。在 propertySources 中添加自定义的
上一篇:BeanDefinitionOverrideException,Spring Data JPA和JDBC bean冲突。
下一篇:BeanDefinitionStoreException: 从类路径资源[applicationContext]解析XML文件时发生IOException异常。