新手详细讲解:spring加载配置文件中的数据
1.首先我们看一下目录结构和要用到的文件
这里我创建了SomeValue2.java,TestCase2.java,BasicValue.xml,db.properties
2.db.properties
3.SomeValue2.java
package Value;
public class SomeValue2 {
private String userName;
public void setUserName(String userName) {
this.userName=userName;
}
@Override
public String toString() {
return "SomeValue2 [userName=" + userName + "]";
}
}
4.BasicValue.xml
配置文件中定义了SomeValue2的bean通过子元素property中userName的set方法赋值,通过db绑定上方读取文件的信息。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<!--
加载配置文件
将其中的数据封装到properties中
spring容器会在类路径下搜索改配置文件
-->
<util:properties id="db" location="classpath:db.properties">
</util:properties>
<bean id="some2" class="Value.SomeValue2">
<!-- 使用spring表达式访问bean属性 -->
<property name="userName" value="#{db.username}"></property>
</bean>
</beans>
4.TestCase2.java
这里的测试类大家就看test6()就行,其他的是之前的测试,谷咕咕懒得删了。
package test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import IOC2.A;
import IOC2.Rest;
import SpringScope.HelloBean;
import SpringScope.PsersonBean;
import Value.BasicValue;
import Value.Page;
import Value.SomeValue;
import Value.SomeValue2;
import Web.UserServlet;
public class TestCase2 {
private ApplicationContext ac;
private final static String XML="BasicValue.xml";
@Before
public void init() {
// ApplicationContext
ac=new ClassPathXmlApplicationContext(XML);
}
@Test
public void test6() {
SomeValue2 some2=ac.getBean("some2",SomeValue2.class);
System.out.println(some2);
}
}
最后我们看下结果,成功将张三这个数据读取了出来