搭建与测试Spring的开发环境
首先在src目录下新建一个beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
</beans>
创建一个借口PersonService.java
package cn.zhhzhy.service;
public interface PersonService {
public abstract void save();
}
在服务层建立一个对上面建立的借口的一个实现类PersonServiceBean.java
package cn.zhhzhy.service.impl;
import cn.zhhzhy.service.PersonService;
public class PersonServiceBean implements PersonService {
public void save(){
System.out.println("保存的方法");
}
}
在beans.xml文件中要引入PersonServiceBean.java
添加这样一个标签<bean id="personService" class="cn.zhhzhy.service.impl.PersonServiceBean"></bean>,对PersonServiceBean.java的引入
最后新建一个测试类
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.zhhzhy.service.PersonService;
public class SpringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception{
}
@Test
public void instanceSpring(){
//传入数组是为了能够引进多了xml文件
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"beans.xml"});
PersonService personService = (PersonService) ctx.getBean("personService");
personService.save();
}
}
输出结果为
2012-7-18 16:37:22 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@110b053: display name [org.springframework.context.support.ClassPathXmlApplicationContext@110b053]; startup date [Wed Jul 18 16:37:22 CST 2012]; root of context hierarchy
2012-7-18 16:37:22 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
2012-7-18 16:37:22 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
信息: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@110b053]: org.springframework.beans.factory.support.DefaultListableBeanFactory@e45076
2012-7-18 16:37:22 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@e45076: defining beans [personService]; root of factory hierarchy
保存的方法
浙公网安备 33010602011771号