完整的junit单元测试及spring配置
XXXXTest.java
private static ClassPathXmlApplicationContext ctx;
/**
* 装入spring配置文件,注入bean
* @throws Exception
*/
@Before
public void setUp() throws Exception {
try {
String[] configLocation = {
"classpath*:spring/applicationContext-*.xml" };
ctx = new ClassPathXmlApplicationContext(configLocation);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
@Test
public void test() {
try {
ClassName aclassobj= (ClassName)ctx.getBean("xmlClassName");
aclassobj.method();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
spring配置文件
1、applicationContext-bean.xml
配置xmlClassName中使用到的成员变量,自动装入,注意ClassName中要有set,get函数
如:
<bean id="xmlClassName" class="ClassNamePackage">
<property name="="***service" ref="***service"/>
<property name="userName" value="${userName}"/>//配置文件中注入
</bean>
2、applicationContext-service.xml
<bean id="="***service" class="="***servicePackage" >
<property name="Path" value="$path}" />//配置文件中注入
</bean>