此仅为个人笔记,若有不周之处,万望指正,不胜感激。
在Spring框架中对象是不需要自己创建的,由容器提供,需要的时候像容器索取即可,这样的好处在于降低代码间耦合,提高代码复用性,且有助于后期维护。Spring框架中主要使用BeanFactory和ApplicationContext两种容器,下面例子使用的是ApplicationContext容器。
ApplicationContext容器的简单使用分以下几步:
- 配置xml文件,配置文件名Spring官方建议使用applicationContext.xml,代码如下:
<bean id="MyService" class="top.bwextend.service.SomeServiceImp1"/>作用等价于:"SomeServiceImp1 MyService=new SomeServiceImp1();"注册Bean等同于使用无参构造函数声明了一个对象,所以必须保证此Bean有无参构造函数。至于参数的初始化,先不做讨论。<?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.xsd"> <!-- 注册Bean --> <bean id="MyService" class="top.bwextend.service.SomeServiceImp1"/> </beans>
- 使用ApplicationContext声明一个容器引用,而ApplicationContext本身是一个接口,所以便用它的实现类ClassPathXmlApplicationContext或FileSystemXmlApplicationContext声明对象。通过ClassPathXmlApplicationContext类来声明容器ApplicationContext对象是在类路径下寻找xml文件,而通过FileSystemXmlApplicationContext类来创建容器ApplicationContext对象是在项目根目录下寻找xml文件,还可以在系统目录下寻找。代码如下:
ClassPathXmlApplicationContext("applicationContext.xml")代码中applicationContext.xml为第一步中配置的xml文件。声明完容器对象之后便可通过容器对象的getBean()方法得到Bean,getBean()方法的参数为xml文件中声明的对应Bean的id属性。package top.bwextend.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import top.bwextend.service.ISomeService; import top.bwextend.service.SomeServiceImp1; public class MyTest { public void test01() { ISomeService service=new SomeServiceImp1(); service.doSome(); } @Test public void test02() { //创建容器对象,加载Spring配置文件 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); ISomeService service=(ISomeService) ac.getBean("MyService"); service.doSome(); } }
- 上述代码中doSome()函数为该Bean的一个方法。