任何人都可以建议为什么我们需要使用静态方法声明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";
}
答案 0 :(得分:19)
PropertySourcesPlaceholderConfigurer
个对象负责解析针对当前Spring环境及其PropertySource集的@Value
注释。 PropertySourcesPlaceholderConfigurer
类实现BeanFactoryPostProcessor
。在容器生命周期中,BeanFactoryPostProcessor
对象必须早于@Configuration
- 注释类的对象进行实例化。
如果你有@Configuration
- 带有实例方法的带注释的类返回PropertySourcesPlaceholderConfigurer
对象,那么容器无法实例化PropertySourcesPlaceholderConfigurer
对象而不实例化@Configuration
- 带注释的类对象本身。在这种情况下,无法解析@Value
,因为PropertySourcesPlaceholderConfigurer
对象在实例化@Configuration
- 注释类的对象时不存在。因此,@Value
- 带注释的字段采用默认值,即null
。
有关详细信息,请参阅@Bean
javadoc的“引导”部分。