[英]About the use of Beans.xml configuration file in Spring Framework application
[英]How to use a properties file in Spring beans XML file?
我有一些属性文件,希望在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阅读Java代码中的more.properties。 不知道为什么您真的需要读取为File Object。
在hello.xml文件中
<!-- Loading all properties files from classpath -->
<bean id="myProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:hello.properties</value>
<value>classpath:more.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="true" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
</bean>
<bean id="theFoo" class="learnspring.Foo">
<property name="color" value="${foo.color}"/>
<property name="shape" value="${foo.shape}"/>
</bean>
在hello.properties文件中
foo.color=blue
在more.properties文件中
foo.shape=square
用Java代码
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("hello.xml");
Foo foo = (Foo) ctx.getBean("theFoo");
System.out.println("Color : " + foo.getColor() +" Shape : " + foo.getShape());
如果您还想遍历bean数据并在jsp上显示其内容。
的hello.xml
<bean id="productManager" class="springapp.service.SimpleProductManager">
<property name="products">
<list>
<ref bean="product1"/>
<ref bean="product2"/>
<ref bean="product3"/>
</list>
</property>
</bean>
<bean id="product1" class="springapp.domain.Product">
<property name="description" value="Lamp"/>
<property name="price" value="5.75"/>
</bean>
<bean id="product2" class="springapp.domain.Product">
<property name="description" value="Table"/>
<property name="price" value="75.25"/>
</bean>
...
为hello.jsp
<c:forEach items="${model.products}" var="prod">
<c:out value="${prod.description}"/>
$<c:out value="${prod.price}"/>
</c:forEach>
参考: Spring.io
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.