一:IOC编程概念
1.IOC控制反转:就是把创建对象(bean)和维护对象关系的权利从程序中转移到spring中容器中,程序的本身不在维护关系和创建对象。
2.di:实际上和IOC是同一个概念,只是认为di表示更准确而已。
二:一个简单的IOC案例
1)编写一个Animal接口
<span style="font-size:18px;">package com.cloud.ioc;
public interface Animal {
public void eat();
public void sleep();
}</span>
2)编写一个Dog类
<span style="font-size:18px;">package com.cloud.ioc;
public class Dog implements Animal{
private String name;
private int age;
@Override
public void eat() {
if(age>3)
System.out.println(name+":今年"+age+"岁了,可以食物");
else
System.out.println(name+":今年"+age+"岁了,不会吃食物");
}
@Override
public void sleep() {
if(age>3)
System.out.println(name+":今年"+age+"岁了,睡觉时间长");
else
System.out.println(name+":今年"+age+"岁了,很活泼");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
</span>
3)applicationContext.xml配置文件
<span style="font-size:18px;"><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<bean id="myDog" class="com.cloud.ioc.Dog">
<property name="name">
<value>小白</value>
</property>
<property name="age">
<value>2</value>
</property>
</bean>
</beans></span>
4)编写测试类
<span style="font-size:18px;">package com.cloud.ioc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestIOC {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Dog dog = (Dog) ac.getBean("myDog");
dog.eat();
dog.sleep();
}
}</span>
三:IOC关系图解