码迷,mamicode.com
首页 > 编程语言 > 详细

spring IOC

时间:2019-01-09 18:53:43      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:vat   enc   owa   war   工厂模式   work   pack   hid   new   

IOC 概念

IOC即控制反转,其借鉴了工厂模式的思想,把实例化对象的代码抽取出来封装到一个地方统一管理。工厂模式是集中到工厂类里统一管理,spring是集中到xml配置文件里统一管理。


 demo

技术分享图片
package com.test.spring;
// 汉武帝
public class HanWudi {
    // 将军
    private General general;

    public HanWudi(General general) {
        this.general = general;
    }
    // order 命令
    public void order() {
        general.goToWar("楼兰");
    }
}
View Code
技术分享图片
package com.test.spring;
// 将军
public interface General {
    public void goToWar(String placeName); // 地方
}
View Code
技术分享图片
package com.test.spring;
// 霍去病
public class HuoQubing implements General {
    @Override
    public void goToWar(String placeName) {
        System.out.println("go to war with " + placeName);
    }
}
View Code
技术分享图片
<?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="king" class="com.test.spring.HanWudi">
        <constructor-arg ref="general"/>
    </bean>
    <bean id="general" class="com.test.spring.HuoQubing"></bean>
</beans>
View Code

 

技术分享图片
package com.test.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Driver {
    private HanWudi hanWudi;

    public static void main(String[] args) {
        // my.xml放在maven项目的resources目录下
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/my.xml");
        HanWudi hanWudi = context.getBean(HanWudi.class);
        hanWudi.order();
        context.close();
    }
}
View Code

 

spring IOC

标签:vat   enc   owa   war   工厂模式   work   pack   hid   new   

原文地址:https://www.cnblogs.com/Mike_Chang/p/10245893.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!