标签:tor control log 微软 一个 测试结果 family 注入 节点
IOC (Inversion of Control) 控制反转
我的理解:将创建对象的控制权从代码本身转交给了外部容器(spring容器)。
1.将组件对象(业务对象)的控制权从代码本身转移到外部容器。
在代码中不使用关键字new来构建一个业务实例,而是在配置文件中。通过xml节点知道容器如何对内存中构建的对应类型的对象名称做命名。
<!-- ioc-->
<bean id="happyService" class="cn.happy.Service.HappyService">
<!-- DI 属性值 依赖注入 -->
<property name="info" value="Spring"></property>
下面来一个墨盒的案例
Ink 颜色 paper 纸张 print 打印机
/**
 * Created by Administrator on 2017/7/23. 墨盒的接口
 */
public interface Ink {
//获取颜色的方法
public String getColor();
/**
 * Created by Administrator on 2017/7/23. 实现类
什么颜色的墨盒
 */
public class GrayInk  implements  Ink{
    public String getColor() {
        return "黑白墨盒";
    }
}
/**
 * Created by Administrator on 2017/7/23. 纸张接口
 */
public interface Paper {
    public  String getPaper();
}
/**
 * Created by Administrator on 2017/7/23. 实现类 B5类型的纸张 
 */
public class B5Paper implements Paper{
    public String getPaper() {
        return "B5纸";
    }
}
**
 * Created by Administrator on 2017/7/23.  打印机
 */
public class Printer {
域属性:
    private Ink  ink;  
    private Paper paper;    
    public  void print(){
  System.out.println("用"+ink.getColor()+"\t颜色的墨盒在"+paper.getPaper()+"\t类型的纸张打印出星期三出去玩儿!没毛病啊");
    }
    public Ink getInk() {
        return ink;
    }
    public void setInk(Ink ink) {
        this.ink = ink;
    }
    public Paper getPaper() {
        return paper;
    }
    public void setPaper(Paper paper) {
        this.paper = paper;
    }
}
配置文件:
<!-- IOC -->
<bean id="happyService" class="cn.happy.Service.HappyService">
    <!-- DI  属性值   依赖注入-->
     <property name="info" value="Spring"></property>
</bean>
 <!--这是彩色墨盒  -->
<bean id="colorInk" class="cn.happy.printer.ink.ColorInk"></bean>
<!--这是纸 -->
<bean id="b5Paper" class="cn.happy.printer.paper.B5Paper"></bean>
<bean id="a4Paper" class="cn.happy.printer.paper.A4Paper"></bean>
<!--这是打印机  -->
 <bean id="pinter"    class="cn.happy.printer.print.Printer">
 <property name="ink" ref="colorInk"></property>
 <property name="paper" ref="b5Paper"></property>
 </bean>
测试类:
public class SpringTest0723 {
 @Test
 public  void test02(){
ApplicationContext  ct= new ClassPathXmlApplicationContext("applicationContext.xml");
  Printer pp =(Printer)ct.getBean("pinter");
   pp.print();
    }
测试结果:

标签:tor control log 微软 一个 测试结果 family 注入 节点
原文地址:http://www.cnblogs.com/wangdan123/p/7398817.html