任何人都可以请建议为什么我们需要使用 a 来声明 PropertySourcesPlaceholderConfigurer beanstatic方法 ?我刚刚发现,如果我在下面使用非静态,那么 url 将被设置为空值,而不是从属性文件中获取 -
@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 环境及其 PropertySource 集的注释。PropertySourcesPlaceholderConfigurer
类工具BeanFactoryPostProcessor
。在容器的生命周期中,BeanFactoryPostProcessor
对象必须早于以下对象实例化@Configuration
-带注释的类。
如果你有@Configuration
- 带实例方法的带注释的类返回PropertySourcesPlaceholderConfigurer
对象,那么容器无法实例化该对象PropertySourcesPlaceholderConfigurer
对象而不实例化@Configuration
- 带注释的类对象本身。在这种情况下,@Value
无法解决,因为PropertySourcesPlaceholderConfigurer
对象在实例化时不存在@Configuration
-带注释的类。因此,@Value
-annotated字段采用默认值,即null
.
请参阅“引导”部分@Bean
javadoc http://docs.spring.io/spring/docs/4.2.x/javadoc-api/org/springframework/context/annotation/Bean.html了解更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)