spring的分散配置

来源:互联网 发布:杨辉三角java代码* 编辑:程序博客网 时间:2024/04/28 11:57
      spring的分散配置    (利用资源文件给xml配置文件里属性赋值)


1,建立配置文件,MyBean.properties


MyBean.properties代码如下:
MyBean.name=\u8D85\u4EBA
MyBean.value=30
dd.title=\u9AD8\u9E4F
2,建立NewMyBean类
NewMyBean.class代码如下:
package cn.entity;


public class NewMyBean {
private String name;
private String value;
private String title;


    .
    .get和set方法省略
    .
}


3,装配config.PropertyPlaceholderConfigurer类  文件名为a.xml
a.xml代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>MyBean.properties</value>
</property>
</bean>
</beans>


4,装配NewMyBean类       文件名为b.xml
b.xml代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


<bean id="newMyBean" class="cn.entity.NewMyBean">
<property name="name">
<value>${MyBean.name}</value>
</property>
<property name="value">
<value>${MyBean.value}</value>    <!--此处是调取资源文件里的值-->
</property>
<property name="title">
<value>${dd.title}</value>
</property>
</bean>
</beans>       


5,最后一步就是测试啦,测试spring的分散配置
测试类代码如下:
    ApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] { "a.xml", "b.xml" });
NewMyBean newMyBean = (NewMyBean) ctx.getBean("newMyBean");// 从容器里取
System.out.println("name:" + newMyBean.getName() + "\n");
System.out.println("value:" + newMyBean.getValue());
System.out.println("title:" + newMyBean.getTitle());                              
原创粉丝点击