spring 容器修改配置文件里值。解密扩展类
1.实现 BeanFactoryPostProcessor
@Configuration
public class ApplicationContextInitializer {
@Bean
public BeanFactoryPostProcessor BeanFactoryPostProcessor() {
return new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
MutablePropertySources propertySources = beanFactory.getBean(ConfigurableEnvironment.class).getPropertySources();
if (!propertySources.contains("PropertySource")) {
PropertySource PropertySource = new PropertySource(propertySources);
propertySources.addFirst(PropertySource);
}
}
};
}
}
- 定义PropertySource 类
public class PropertySource extends PropertySource {
public static final String PUB_KEY = "MIKSECPUBLIC";
private static final String PREFIX = "enc(";
private static final String SUFFIX = ")";
private static final Logger LOGGER = LoggerFactory.getLogger(PropertySource.class);
private MutablePropertySources originalPropertySource;
public PropertySource(MutablePropertySources originalPropertySource) {
super("PropertySource", originalPropertySource);
this.originalPropertySource = originalPropertySource;
}
@Override
public String getName() {
return super.getName();
}
@Override
public Object getSource() {
return super.getSource();
}
@Override
public boolean containsProperty(String name) {
for (PropertySource propertySource : originalPropertySource) {
if (propertySource instanceof PropertySource) {
continue;
}
if (propertySource.containsProperty(name)) {
return true;
}
}
return false;
}
@Override
public boolean equals(Object other) {
return super.equals(other);
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
return super.toString();
}
@Override
public Object getProperty(String name) {
for (PropertySource propertySource : originalPropertySource) {
if (propertySource instanceof PropertySource) {
continue;
}
if (propertySource.getClass().getName().contains("ConfigurationPropertySourcesPropertySource")) {
continue;
}
if (propertySource.containsProperty(name)) {
Object value = propertySource.getProperty(name);
if (value instanceof String) {
String str = value.toString();
if (str.startsWith(PREFIX) && str.endsWith(SUFFIX)) {
int startIndex = 4;
int endIndex = str.length() - 1;
String encValue = str.substring(startIndex, endIndex);
return RSAUtils.decryptByPublic(encValue, RSAUtils.getPublicKey(RSAUtils.getPubKey()));
}
}
}
}
return null;
}