- IOC与DI
- IOC举例
- Java IoC简单例子
IOC与DI
IOC,Inversion of Control,控制倒转。这是spring的核心,贯穿始终。所谓IoC,对于spring框架来说,就是由spring来负责控制对象的生命周期和对象间的关系。
DI,Dependency Injection,依赖注入。在系统运行中,动态的向某个对象提供它所需要的其他对象。
控制的什么被反转了?就是:获得依赖对象的方式反转了。
IOC举例
如何找女朋友的?
常见的情况是,我们到处去看哪里有长得漂亮身材又好的mm,然后打听她们的兴趣爱好、微信号、qq号、电话号等等,想办法认识她们,投其所好送其所要,然后嘿嘿……这个过程是复杂深奥的,我们必须自己设计和面对每个环节。
传统的程序开发
在一个对象中,如果要使用另外的对象,就必须得到它(自己new一个,或者从JNDI中查询一个),使用完之后还要将对象销毁(比如Connection等),对象始终会和其他的接口或类藕合起来。
那么IoC是如何做的呢?
有点类似婚介所,一个婚介所有很多男男女女的个人信息,我可以向婚介所提出要求,比如长得像高圆圆,身材像林熙蕾等等,然后婚介所就会按照我们的要求,提供符合要求的一个mm信息,我们只需要去和mm谈朋友就好了。如果婚介所给我们的人选不符合要求,我们就提出不交往。整个过程不再由我自己来控制,而是由婚介所类控制中间环节。Spring开发也是如此,所有的类都会在Spring容器中登记,告诉Spring你是什么,你需要什么,然后Spring会在系统运行到适当的时候,把你需要的东西主动给你,同时也把你交给其他需要的你的类。所有类的创建、销毁都由Spring来控制,也就是说控制对象生存周期不再是引用它的对象,而是Spring。对于某个对象而言,以前是它控制其他对象,现在是所有对象都被spring控制,所以就叫控制反转。
Java IOC简单例子
首先创建动物接口Animal
package com.feiniu.springframework.test;
public interface Animal {
public void say();
}
接着创建动物实现类Cat
package com.feiniu.springframework.test;
public class Cat implements Animal{
private String name;
@Override
public void say() {
System.out.println("I am " + name + "!");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
然后创建配置文件applicationContext.xml以及配置Cat类
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"
default-autowire="byName">
<bean id="animal" class="com.feiniu.springframework.test.Cat">
<property name="name" value="kitty" />
</bean>
</beans>
最后创建测试类TestAnimal
package com.feiniu.springframework.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestAnimal {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext(
"applicationContext.xml");
Animal animal = (Animal) context.getBean("animal");
animal.say();
}
}
执行main方法控制台结果
I am kitty!