基于Spring Java的静态方法配置

Shr*_*res 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";
}
Run Code Online (Sandbox Code Playgroud)

Con*_*ine 20

PropertySourcesPlaceholderConfigurer对象负责解析@Value当前Spring环境及其PropertySources集合的注释.PropertySourcesPlaceholderConfigurer类实现BeanFactoryPostProcessor.在容器生命周期中,BeanFactoryPostProcessor必须比@Configuration注释类的对象更早地实例化对象.

如果您@Configuration使用实例方法返回一个PropertySourcesPlaceholderConfigurer对象来注释类,那么容器无法在PropertySourcesPlaceholderConfigurer不实例化@Configuration注释类对象本身的情况下实例化该对象.在这种情况下,@Value无法解析,因为在PropertySourcesPlaceholderConfigurer实例化@Configuration注释类的对象时该对象不存在.因此,@Value-annotated字段采用默认值,即null.

有关更多信息,请参阅@Bean javadoc的"Bootstrapping"部分.