在spring中使用带有beanfactory的property-placeholder

时间:2016-12-13 15:16:54

标签: spring property-placeholder

使用以下XML配置

distinct

我使用以下2个选项在main中创建了一个bean: 1)使用ClassPathXmlApplicationContext 2)使用bean因子

使用ClassPathXmlApplicationContext创建bean时设置动态值,但使用bean工厂创建时则不设置动态值。

您能否建议如何使用bean工厂使其工作?

提前致谢。

1 个答案:

答案 0 :(得分:0)

对bean属性使用 XML 声明时, property-placeholder 被注册为IoC容器的Bean Factory Post Processor,因此您将拥有属性值可用。

但是,当通过BeanFactory以编程方式实例化bean时,除非你配置``作为后处理器,否则这个工厂不会知道属性值:

BeanFactory factory = /* your factory initialized */;
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("constants.properties"));
cfg.postProcessBeanFactory(factory);

修改

请注意,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#setLocation接受org.springframework.core.io.Resource作为其参数,即您可以根据需要使用其具体的子实现:

  • org.springframework.core.io.FileSystemResource:支持文件句柄的实现。
  • org.springframework.core.io.ClassPathResource:类路径资源的实现。
  • org.springframework.core.io.InputStreamResourceInputStream ...
  • 的实现