简单记录问题排查中学习到的知识,欢迎大神修正、补充与完善
加载自定义配置文件4种方式
-
第一种:
继承org.springframework.context.support.PropertySourcesPlaceholderConfigurer类,主要重写mergeProperties()方法,然后注入成bean.
/** 配置解密,只能自定义一个PropertySourcesPlaceholderConfigurer,否则会报异常 **/
public class EncryptPropertyPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer implements InitializingBean {
/** 需要解密的配置项前缀 */
private static final String PREFIX_ENC = "enc:";
@Override
protected Properties mergeProperties() throws IOException {
Properties mergedProperties = new Properties();
for (Properties localProp : localProperties) {
mergedProperties.putAll(localProp);
}
for (Map.Entry entry : mergedProperties.entrySet()) {
if (entry.getValue().toString().startsWith(PREFIX_ENC)) {
String key = System.getProperty("enc.key");
String value = entry.getValue().toString().replace(PREFIX_ENC, StringUtils.EMPTY);
mergedProperties.setProperty(entry.getKey().toString(), AESUtil.decode(value, key));
}
}
//针对sharding-jdbc datasource自定义解密的特殊处理
//因为sharding-jdbc的datasource注入是从environment中获取propertySource,
//不能直接通过PropertySourcesPlaceholderConfigurer定义的resource获取
MutablePropertySources sources = ((ConfigurableEnvironment) environment).getPropertySources();
sources.addFirst(new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergedProperties));
return mergedProperties;
}
@Override
public void afterPropertiesSet() throws Exception {
localOverride = true;
}
}
@Bean
public PropertySourcesPlaceholderConfigurer propertyConfigurer() {
PropertySourcesPlaceholderConfigurer config = new EncryptPropertyPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("application-dev.yml"));
config.setProperties(yaml.getObject());
return config;
}
-
第二种:
application.yml文件引用方式,被引用文件的文件名格式"application-*.yml",文件放置范围与springboot默认配置文件(4个路径)路径相同
spring:
profiles:
include: aliConfig
-
第三种:
注解方式,如果为yml文件,需要自定义解析类
@PropertySource(value= {"classpath:aliConfig$a.yml"},factory=InitAliConfig.class)
public class InitAliConfig implements PropertySourceFactory{
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
// 重写这个方法
}
}
-
第四种:
启动类properties属性设置:
SpringApplication sa = new SpringApplication(ZyglScheduleJobApplication.class);
sa.setDefaultProperties(new InitAliConfig().initAliConfig());
sa.run(args);
单元测试加载方式
完全支持第一种和第二种
第三种只支持properties文件,不支持yml文件
不支持第四种方式,无设置入口