在搭建spring环境之前,我们需要知道spring是解决对象创建的问题,可以说spring是万能的,不管是持久层,业务层,还是控制层都会用到spring而前边我们搭建的struts和hibernate现在大多数企业已经不用了,但这并不是说我们可以不学了,现在大多数企业在解决控制层较多的使用Spring MVC在解决持久层较多的是使用MyBatis虽然技术在不断地更新,但只要把struts,hibernate,spring再学其他的就会非常的容易,接下来就进入主题
1:创建一个web工程,并把下载好的jar包全部复制到到/WEB-INF/lib目录下(jar包下载地址:http://pan.baidu.com/s/1skSoftr)
2,把bean.xml文件放到src目录下,bean.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">
<!-- id 这个值是随意取的,为了规范化我们一般类名的第一个字母小写 class的值是把那个类放入ioc容器 -->
<bean id="personService" class="cn.wxz.service.impl.PersonServiceBean"></bean>
</beans>
3:进行测试,我们在开发中在持久层和业务层都是面向接口的开发,先定义一个接口IPersonService然后在创建一个PersonService实现IPersonService接口。
3.1 IPersonService代码
package cn.wxz.service;
public interface IPersonService {
public void save();
}
3.2 PersonService代码如下
package cn.wxz.service.impl;
import cn.wxz.service.IPersonService;
public class PersonService implements IPersonService {
public void save(){
System.out.println("成功调用了save()方法");
}
}
3.3 测试类SpringTest代码如下
package junit.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.wxz.service.IPersonService;
public class SpringTest {
@Test public void instanceSpring(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
IPersonService iPersonService = (IPersonService)ctx.getBean("personService");
iPersonService.save();
}
}
3.4运行方法在控制台看到如下,可知搭建环境成功
注意这里我们没有通过 new PersonService这个类而获取这个类的方法而是通过ioc容器获取到PersonService而调用save方法。