初学Spring,会被其中一些晦涩到莫名其妙在名词搞到头大,理一理他们的关系,一下就豁然开朗了。
bean
bean是啥?bean是对象,在Java中,我们叫他java bean。到了Spring中,就得入乡随俗,我们叫他Spring bean。更确切的说,Spring bean是被Spring IoC容器所管理的bean对象。
IoC
第二个概念,IoC 又是个什么高科技? IoC(Inverse of Control)中文译作:控制反转。
控制反转
这个其实还好理解,就是控制权利发生了易主。
具体到Spring中,以前我们创建对象是这样的:Foo foo = new Foo();
现在创建对象这个控制权由Spring接管了,我们可以直接拿起对象就用,因为Spring已经帮我们创建好对象了。
一句话总结:对象的创建权从程序员手中反转到了Spring手中
Spring IoC容器
要理解Spring IoC容器,需要先明白容器就是存取东西(对象)的地方。Spring IoC容器中存放的正是一个个的Spring bean对象。
似懂非懂?是不是想知道Spring IoC容器的具体形态,也就是Spring IoC容器长什么样?
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("springApplication.xml");以上的这句代码是不是特别熟悉,是的。ApplicationContext 就是Spring IoC的容器
重要的事情变着花的写三遍:
ApplicationContext 就是Spring IoC的容器
ApplicationContext 就是Spring IoC的具体形态
ApplicationContext 就是Spring IoC的容器的长相
Spring IoC 容器中的 bean 来自哪里
来自我们非常熟悉的配置文件beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="mybean" class="com.wlmqtc.www.pojo.MyBean">
<property name="what" value="This is a bean" />
</bean>
</beans>bean 的装配
装配是什么?就是组装。例如装配一辆汽车bean, 这个汽车bean 还需要发动机bean, 轮子bean等等……
嗯……我们想要一台真正能动的汽车,下面就是注入灵魂的时刻,我们把发动机bean, 轮子bean等等 注入到 汽车bean中,因为汽车bean依赖其他对象。这个注入又叫做依赖注入 DI
DI
DI全拼(Dependency Injection)中文翻译:依赖注入。正如上面讲到的《bean的装配》的例子。
Spring 容器要创建一个bean,这个bean又依赖其他bean。依赖哪个bean,就在内部注入bean,这就是依赖注入。
以下的
<beans>
<bean id="car" class="com.wlmqtc.Car">
<property name="engine" ref="engine">
<property name="wheel" ref="wheel">
<bean>
<bean id="engine" class="com.wlmqtc.Engine">
<property name="brank" value="audi">
<bean>
<bean id="wheel" class="com.wlmqtc.Wheel">
<property name="orign" value="china">
<bean>
<beans>