Spring IoC / DI 实现步骤
-
配置元数据(配置)
配置元数据,既是编写交给SpringIoC容器管理组件的信息,配置方式有三种。
基于 XML 的配置元数据的基本结构:
<bean id=“…” [1] class=“…” [2]>
<!-- collaborators and configuration for this bean go here -->
</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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="..." [1] class="..." [2]> <!-- collaborators and configuration for this bean go here --> </bean> <bean id="..." class="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- more bean definitions go here --> </beans>
Spring IoC 容器管理一个或多个组件。这些 组件是使用你提供给容器的配置元数据(例如,以 XML
<bean/>
定义的形式)创建的。<bean /> 标签 == 组件信息声明
id
属性是标识单个 Bean 定义的字符串。class
属性定义 Bean 的类型并使用完全限定的类名。
-
实例化IoC容器
提供给
ApplicationContext
构造函数的位置路径是资源字符串地址,允许容器从各种外部资源(如本地文件系统、JavaCLASSPATH
等)加载配置元数据。我们应该选择一个合适的容器实现类,进行IoC容器的实例化工作:
//实例化ioc容器,读取外部配置文件,最终会在容器内进行ioc和di动作 ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
-
获取Bean(组件)
ApplicationContext
是一个高级工厂的接口,能够维护不同 bean 及其依赖项的注册表。通过使用方法T getBean(String name, Class<T> requiredType)
,您可以检索 bean 的实例。允许读取 Bean 定义并访问它们,如以下示例所示:
//创建ioc容器对象,指定配置文件,ioc也开始实例组件对象 ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml"); //获取ioc容器的组件对象 PetStoreService service = context.getBean("petStore", PetStoreService.class); //使用组件对象 List<String> userList = service.getUsernameList();