Spring Java based configuration with static method

2019-03-15 08:54发布

问题:

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";
}

回答1:

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.