Consider the following setup:
@Configuration
@PropertySource("classpath:common.properties")
public class CommonConfig {
}
Now let's assume that I want some non-trivial logic behind how and what property sources I load in this config, and I want to use the properties API for this:
@Configuration
public class CommonConfig {
@Autowired
private ConfigurableEnvironment env;
public void loadCommonConfig() {
// Determine what properties to load and how...
env.getPropertySources().addLast(...);
}
}
I don't understand how I'm supposed to notify Spring that I am interested in loadCommonConfig
to be called in the point in the life cycle where @PropertySource
would have been handled. Simply returned the properties as a @Bean
did not seem to work.
Spring @PropertySource annotation is used to provide properties file to Spring Environment. This annotation is used with @Configuration classes. Spring PropertySource annotation is repeatable, means you can have multiple PropertySource on a Configuration class.
Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.
Register a Properties File via Annotations Spring 3.1 also introduces the new @PropertySource annotation as a convenient mechanism for adding property sources to the environment. We can use this annotation in conjunction with the @Configuration annotation: @Configuration @PropertySource("classpath:foo.
Adding Message Properties Into The Spring Boot Project In order to do that, just create two files in src/main/resources/messages folder with naming as below, api_error_messages. properties. api_response_messages.
You must declare a PropertySourcesPlaceholderConfigurer
static bean for @PropertySource
annotations to work (or use SpringBoot that will declare it for you).
You can manually load properties files when declaring this bean, with method setLocations(...)
.
Here's an example :
@Configuration
public class CommonConfig {
...
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
ppc.setLocations(new FileSystemResource("/etc/webapp_properties/security-token.properties"),
new ClassPathResource("config/WebApp.properties"),
new ClassPathResource("config/" + System.getenv("CURRENTENV") + "/WebApp.properties"));
return ppc;
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With