1-IOC和DI

目录 G:\8-CodeCloud\spring
项目名称 spring_ioc
项目文件夹 com.imooc.initial;com.imooc.ioc.demo1

1. IOC

Inverse of Control 控制反转=工厂+反射+配置文件

1.1 原理
传统的对象离不开new,对象的调用随意没有管理。
而IOC的机制:让Spring来管理对象,对象的生成同一由applicationContext.getBean来生成。
传统机制与IOC机制的原理如下图所示:

传统机制与IOC原理.png

从new—>面向接口编程—>工厂模式—>IOC机制,简单的代码如下:

public class Test {
    public static void main(String[] args) {
        UserServiceSimple serviceOne = new UserServiceSimple();
        serviceOne.setName("模式一:原始的方法");
        serviceOne.show();

        System.out.println("----------------------------------------------------------");

        /*接口为了统一的标准*/
        UserService userService = new UserServiceImpl("模式二:采用接口的形式");
        userService.show();

        System.out.println("----------------------------------------------------------");


        /*工厂的好处是只需要修改工厂类,而不需要动其他代码*/
        UserService userServiceOne = FactoryUserService.getUserServiceBean("模式三:采用工厂的形式");
        userServiceOne.show();

        /*Spring IOC  控制反转
          工厂+反射+配置文件

          配置文件注册:<bean id="userServiceImpl" class="com.imooc.initial.UserServiceImpl">
          工厂
                       public static object getBean(String id){
                                    反射
                       }
        */
    }
}

1.2 示例
通过applicationContext.getBean的方式来获取对象,注意利用junit的测试方法,后续可以专门研究。

package com.imooc.ioc.demo1;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDemo1 {

    @Test
    /**
     * 传统方法开发
     */
    public void demo1(){

        //UserService userService = new UserServiceImpl();
        UserServiceImpl userService = new UserServiceImpl();
        //设置属性
        userService.setName("超人");
        userService.sayHello();
    }

    @Test
    /**
     * Spring方式实现:实际上还是通过spring工厂类获得bean
     */
    public  void demo2(){
        //创建spring的工厂
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) applicationContext.getBean("userService");
        userService.sayHello();

    }
}

2. DI

Dependency Injection 依赖注入=通过Spring框架新建对象的同时,对其初始化
假设UserServiceImpl有name属性,那么在applicationContext.xml中即可对其初始化

    <bean id="userService"  class="com.imooc.ioc.demo1.UserServiceImpl">  <!--控制反转-->
        <!--设置属性-->
        <property name="name" value="我本超人"/>  <!--依赖注入-->
    </bean>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容