1, @ PropertySource anotação modo
recurso personalizado arquivos 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, implementar a interface de 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 adicionar o EnvironmentPostProcessor
3, adicionado directamente ao meio ambiente em
@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));
}
}
}
Faça o teste
@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);
}
}
No entanto, esta abordagem deve prestar atenção para carregar a configuração do feijão de dar prioridade para obter a configuração do feijão é carregado.
4, spring.profile.include
O arquivo de configuração foi renomeada application-custom.properties
spring.profile.include direta a aumentar em application.properites no.
spring.profiles.include=custom