【发布时间】:2017-04-30 18:41:21
【问题描述】:
我想在 Spring XML 配置文件中提供一些属性文件。例如在hello.xml:
<bean id="theFoo" class="learnspring.Foo">
<property name="color" value="${foo.color}"/>
</bean>
在 Java 代码中:
ApplicationContext ac = new ClassPathXmlApplicationContext("hello.xml");
File props = new File("path/to/hello.properties");
File moreProps = new File("path/to/more.properties");
// What to do here?
Foo foo = (Foo)ac.getBean("theFoo");
System.out.println(foo.getColor());
在hello.properties:
foo.color = blue
如何使属性文件可用于 Spring 对象定义?
更新
我正在移植一些旧的 Spring 代码。 (2.5 版)看起来有点像这样:
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(xmlFile));
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
cfg.setLocations(new Resource[] {
new ClassPathResource(propsResourcePath),
new FileSystemResource(propsFile)) });
cfg.postProcessBeanFactory(factory);
new GenericApplicationContext(factory);
此代码已被标记为已弃用,并且我遇到了其他问题,因此我尝试将其移植到新方式。
【问题讨论】:
-
也许是
PropertyPlaceHolderConfigurer? docs.spring.io/spring/docs/2.5.x/reference/… -
这显示了如何在 XML 文件中硬编码属性路径,但是如果我在 Java 代码中有一些
File对象怎么办?