基于Spring Java的静态方法配置 [英] Spring Java based configuration with static method

查看:62
本文介绍了基于Spring Java的静态方法配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

can any one please advice why we need to declare PropertySourcesPlaceholderConfigurer bean using a static method ? I just found that if I use non-static for below then url will be set to null value instead of taking from property file -

@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对象负责针对当前Spring Environment及其PropertySources集解析@Value批注. PropertySourcesPlaceholderConfigurer类实现BeanFactoryPostProcessor.在容器生命周期中,必须早于@Configuration注释类的对象实例化BeanFactoryPostProcessor对象.

PropertySourcesPlaceholderConfigurer objects are responsible for resolving @Value annotations against the current Spring Environment and its set of PropertySources. PropertySourcesPlaceholderConfigurer class implements BeanFactoryPostProcessor. In the container lifecycle, a BeanFactoryPostProcessor object must be instantiated earlier than an object of @Configuration-annotated class.

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

If you have @Configuration-annotated class with instance method returning a PropertySourcesPlaceholderConfigurer object, then the container can not instantiate the PropertySourcesPlaceholderConfigurer object without instantiating the @Configuration-annotated class object itself. In this case, @Value can not be resolved, since the PropertySourcesPlaceholderConfigurer object does not exist at the moment of instantiation of the object of @Configuration-annotated class. Thus, @Value-annotated field takes the default value, which is null.

请参见@Bean javadoc 了解更多信息.

Please see the "Bootstrapping" part of @Bean javadoc for more information.

这篇关于基于Spring Java的静态方法配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆