Chapter1、搭建与测试spring的环境
1、 将必要的jar包导入到新建的project中(可以去官网下载,也可以google或者百度)至少必须使用的有spring.jar 和commons-logging.jar
2、 在calsspath路径下创建配置文件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"> <bean id="" class=""></bean> </beans>
3、 实例化spring容器:
实例化Spring容器的两种方式:
(1)在类路径下寻找配置文件来实例化容器
ApplicationContext ctx = new ClassPathXmlApplicationXContext(new String[]{“beans.xml”})
(2)在文件系统路径下寻找配置文件来实例化容器
ApplicationContext ctx = new FileSystemXmlApplication(new String[]{“d:\\beans.xml”});
Spring 的配置文件可以指定多个,可以通过String数组传入,也可以是一个String
public class Test { public static void main(String[] args) { //IOC容器实例化 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); } }
Spring环境搭建成功!
4、创建业务bean接口 :
package com.wxy.service; public interface PeopleService { public abstract void save(); }
5、实现业务bean接口:
package com.wxy.service.impl; import com.wxy.service.PeopleService; public class PeopleServiceBean implements PeopleService { /* (non-Javadoc) * @see com.wxy.service.impl.PeopleService#save() */ public void save() { System.out.println("--> the method is called save()!"); } }
6、 在beans.xml中配置业务bean,将bean交给spring容器管理,spring创建和维护该bean,用户使用时,只需要获取就可以了,不用自己创建,实现IoC
依赖倒置。
<?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"> <bean id="peopleService" class="com.wxy.service.impl.PeopleServiceBean"></bean> </beans>
7、 使用业务bean:
public class Test { public static void main(String[] args) { //IOC容器实例化 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); //获取业务bean PeopleServiceBean peopleService = (PeopleServiceBean) ctx.getBean("peopleService"); peopleService.save(); } }