基于Spring Java的静态方法配置

时间:2015-08-01 15:05:13

标签: spring-mvc spring-java-config

任何人都可以建议为什么我们需要使用静态方法声明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";
}

1 个答案:

答案 0 :(得分:19)

PropertySourcesPlaceholderConfigurer个对象负责解析针对当前Spring环境及其PropertySource集的@Value注释。 PropertySourcesPlaceholderConfigurer类实现BeanFactoryPostProcessor。在容器生命周期中,BeanFactoryPostProcessor对象必须早于@Configuration - 注释类的对象进行实例化。

如果你有@Configuration - 带有实例方法的带注释的类返回PropertySourcesPlaceholderConfigurer对象,那么容​​器无法实例化PropertySourcesPlaceholderConfigurer对象而不实例化@Configuration - 带注释的类对象本身。在这种情况下,无法解析@Value,因为PropertySourcesPlaceholderConfigurer对象在实例化@Configuration - 注释类的对象时不存在。因此,@Value - 带注释的字段采用默认值,即null

有关详细信息,请参阅@Bean javadoc的“引导”部分。