can any one please advice why we need to declare PropertySourcesPlaceholderConfigurer bean using a static method ? I just found that if I use non-static for below then url will be set to null value instead of taking from property file -
@Value("${spring.datasource.url}")
private String url;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfig(String profile) {
String propertyFileName = "application_"+profile+".properties";
System.out.println(propertyFileName);
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setLocation(new ClassPathResource(propertyFileName));
return configurer;
}
@Bean
@Profile("local")
public static String localProfile(){
return "local";
}
@Bean
@Profile("prod")
public static String prodProfile(){
return "prod";
}
Yes, A spring bean may have static methods too. The idea here is to hand over a bean to a static field after bean is configured by spring.
Afterward, we want to inject its value to an instance variable. That's because Spring doesn't support @Value on static fields.
They are similar, but have subtle differences. Instead of having an @Component annotation on your class( which is annotation-based configuration ), you can skip the @Component and instead have a @Bean annotated method which returns a new instance of this class. ( this is Java-based configuration).
@Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite' mode.
PropertySourcesPlaceholderConfigurer
objects are responsible for resolving @Value
annotations against the current Spring Environment and its set of PropertySources. PropertySourcesPlaceholderConfigurer
class implements BeanFactoryPostProcessor
. In the container lifecycle, a BeanFactoryPostProcessor
object must be instantiated earlier than an object of @Configuration
-annotated class.
If you have @Configuration
-annotated class with instance method returning a PropertySourcesPlaceholderConfigurer
object, then the container can not instantiate the PropertySourcesPlaceholderConfigurer
object without instantiating the @Configuration
-annotated class object itself. In this case, @Value
can not be resolved, since the PropertySourcesPlaceholderConfigurer
object does not exist at the moment of instantiation of the object of @Configuration
-annotated class. Thus, @Value
-annotated field takes the default value, which is null
.
Please see the "Bootstrapping" part of @Bean
javadoc for more information.
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