概念
控制反转,对象定义跟他们协作的对象,就是依赖,通过构造器参数,参数给一个工厂方法,或者实例化对象的属性
It is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method.
我们在用的时候,一般都是不需要构造器参数的,倒是有属性的。
ApplicationContext
负责实例化,配置,聚集这些beans,容器通过读取配置元数据获得如何初始化,配置元数据在XML,java注解,或者java代码。一般重用xml和注解吧。
常用的实现是:
ClassPathXmlApplicationContext
or FileSystemXmlApplicationContext
下图是:The Spring IoC container
配置文件
下面就开始准备需要的内容,首先是配置元素
最基础的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"> <bean id="..." class="..."> <!-- 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>
实例化容器
直接在配置文件中指定配置文件路径就可以了,比如
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});