基于Spring Java的静态方法配置


问题内容

谁能建议我们为什么需要使用 静态 方法声明PropertySourcesPlaceholderConfigurer bean
?我只是发现,如果我在下面使用非静态方法,则url将被设置为null值,而不是从属性文件中获取-

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

问题答案:

PropertySourcesPlaceholderConfigurer对象负责@Value根据当前的Spring
Environment及其PropertySources集解析注释。PropertySourcesPlaceholderConfigurer类工具BeanFactoryPostProcessor。在容器生命周期中,BeanFactoryPostProcessor必须早于@Configuration-annotated类的对象实例化对象。

如果@Configuration具有实例化方法的-
annotated类返回一个PropertySourcesPlaceholderConfigurer对象,则容器无法实例化该PropertySourcesPlaceholderConfigurer对象,而无需实例化@Configuration-annotated类对象本身。在这种情况下,@Value由于-
annotated类PropertySourcesPlaceholderConfigurer的对象实例化时该对象不存在,因此无法解决@Configuration。因此,@Value-annotated字段采用默认值,即null

有关更多信息,请参见@Bean javadoc的“ Bootstrapping”部分。