Spring基础二—Ioc容器
一.概述
在Spring中,依赖注入叫做Ioc(控制反转),业务类的实例称为bean,IoC容器负责对bean进行实例化,组装和管理。bean及其之间的依赖关系反映在容器使用的配置元数据中。
在Spring框架中,org.springframework.context.ApplicationContext代表Spring IoC容器。容器通过读取配置元数据获取有关需要实例化,配置和组装对象的指令。配置元数据以XML,注解表示。它允许您表达组成应用程序的对象以及这些对象之间丰富的相互依赖性。在应用中,通常通过创建ClassPathXmlApplicationContext 或 FileSystemXmlApplicationContext实例来获取bean。
二.容器实例化
实例化Spring IoC容器非常简单。提供给ApplicationContext构造函数XML配置文件的地址即可。
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml");
以下示例显示了服务层对象(services.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.xsd">
<!-- services -->
<bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for services go here -->
</beans>
在上面的示例中,服务层由类PetStoreServiceImpl,和类型的两个数据访问对象JpaAccountDao和JpaItemDao。该property name元素是指JavaBean属性的名称,以及ref元素指的是另一个bean定义的名称。元素id和ref元素之间的这种联系表达了协作对象之间的依赖关系。
三.容器使用
ApplicationContext是高级工厂的接口,能够维护不同bean及其依赖项的注册表。使用该方法,T getBean(String name, Class requiredType)便可以获取bean的实例,代码如下:
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
PetStoreService service = context.getBean("petStore", PetStoreService.class);
List<String> userList = service.getUsernameList();