'External properties file in spring
I have a java,spring and not spring boot command line program with maven , which when i build a jar with all dependencies using maven-assembly-plugin , it includes application.properties, what i need to know is how to read the external application.properties and not the jar one.
I am reading the property file as:
@PropertySource(value = { "classpath:application.properties" })
If I print the classpath, the classpath does only include the jar and not the current directory.
Solution 1:[1]
Here is what you can do:
@PropertySources({
@PropertySource("classpath:application.properties"),
@PropertySource(value = "file:/etc/config/my-custom-config.properties", ignoreResourceNotFound = true)
})
This ignoreResourceNotFound
is available since spring 4.3 and is pretty self-explanatory.
You can also opt for "programmatic" approach. In pure spring (not spring boot as you've mentioned in the question):
@Configuration
public class CommonConfig {
...
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
ppc.setLocations(new FileSystemResource("/etc/config/my-custom-config.properties"),
new ClassPathResource("config/application.properties"),
return ppc;
}
...
}
FileSystemResource
is for accessing resources available externally in the file system
ClassPathResource
is for accessing resources in the classpath
Solution 2:[2]
We use dynamically generated configuration files that are injected with environment specific secrets. The combination to get everything aligned is as follows:
Code:
myFunction(@Value("${custom.configuration.name}") final String customConfigurationName) {
InputStream inputStream=new ClassPathResource(customconfigFileName).getInputStream()){}
...
}
Template - Add a hard required path as this confirms the file is on disk and loaded:
- name: SPRING_CONFIG_LOCATION
value: file:./config/schema-${ENV}.yml
...
- name: custom.configuration.name
value: file:config/schema-${ENV}.yml
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mark Bramnik |
Solution 2 | Lodlaiden |