1、@PropertySource注解方式
自定义资源文件custom.properties
@Configuration
@PropertySource(value = "custom.properties")
public class EnvironmentTest implements CommandLineRunner{
@Value("${test.param1:}")
private String param1;
@Override
public void run(String... strings) throws Exception {
System.out.println("read test.param1: "+param1);
}
}
2、实现接口EnvironmentPostProcessor
public class CustomEnvironmentPostProcessor implements EnvironmentPostProcessor {
private final Properties properties = new Properties();
/**
* The Profiles.
*/
private String[] profiles = {
"custom.properties",
};
@Override
public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
for (String profile : profiles) {
Resource resource = new ClassPathResource(profile);
configurableEnvironment.getPropertySources().addLast(loadProfiles(resource));
}
}
private PropertySource<?> loadProfiles(Resource resource) {
if (!resource.exists()) {
throw new IllegalArgumentException("file" + resource + "not exist");
}
try {
properties.load(resource.getInputStream());
return new PropertiesPropertySource(resource.getFilename(), properties);
} catch (IOException ex) {
throw new IllegalStateException("load resource exception" + resource, ex);
}
}
}
spring.factories中添加该EnvironmentPostProcessor
3、直接往environment中添加
@Configuration
public class CustomPropertiesLoadConfig {
@Autowired
private Environment environment;
@PostConstruct
public void load(){
if(environment instanceof StandardEnvironment){
MutablePropertySources propertySources = ((StandardEnvironment) environment).getPropertySources();
Resource resource = new ClassPathResource("custom.properties");
Properties properties = new Properties();
try {
properties.load(resource.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
propertySources.addFirst(new PropertiesPropertySource("customPorperties", properties));
}
}
}
获取测试
@Configuration
public class EnvironmentTest implements CommandLineRunner {
@Value("${test.param1:}")
private String param1;
@Override
public void run(String... strings) throws Exception {
System.out.println("read test.param1: "+ param1);
}
}
但是这种方式要注意加载配置的bean一定要优先于获取配置的bean加载。
4、spring.profile.include
将配置文件改名为application-custom.properties
直接在application.properites中增加spring.profile.include即可。
spring.profiles.include=custom