Spring IOC,DI注入(依赖注入)最简明理解

通过例子认识IOC并作出总结:

假设我们现在有一个接口HelloService,然后有一个实现类HelloServiceImpl

public interface HelloService {
    public void saHello();
}

HelloServiceImpl

public class HelloServiceImpl implements HelloService {
    @Override
    public void saHello() {
        System.out.println("Hello");
    }
}

传统方法我们进行测试

public class HelloServiceTest {
    public static void main(String[] args) {
        HelloService helloService=new HelloServiceImpl();
        helloService.saHello();
    }
}

输出结果:Hello


如果我们使用IOC控制反转的话

现在配置文件(applicationContext.xml)中配置添加Bean

<bean id="helloService" class="com.service.impl.HelloServiceImpl"/>

然后进行测试 

public class HelloServiceTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext= new ClassPathXmlApplicationContext("applicationContext.xml");

        HelloService helloService=(HelloService)applicationContext.getBean("helloService");
        helloService.saHello();
    }
}

拿到结果:Hello


那么当我实现类里面有属性的时候(修改HelloServiceImpl的代码,添加String属性)

public class HelloServiceImpl implements HelloService {

    private String name;

    @Override
    public void saHello() {
        System.out.println("Hello"+name);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

进行测试 

public class HelloServiceTest {
    public static void main(String[] args) {
        HelloServiceImpl helloService=new HelloServiceImpl();
        helloService.setName("World");
        helloService.saHello();
    }
}

输出结果:HelloWorld 


 我们使用IOC的DI注入属性的方式(修改配置文件代码)

  <bean id="helloService" class="com.service.impl.HelloServiceImpl">
       <!--设置属性-->
        <property name="name" value="World"></property>
  </bean>
public class HelloServiceTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext= new ClassPathXmlApplicationContext("applicationContext.xml");

        HelloService helloService=(HelloService)applicationContext.getBean("helloService");
        helloService.saHello();
    }
}

输出结果:HelloWorld  


通过上面的例子我们可以的发现

IOC:IOC是将我们接口的控制权转交给Spring进行管理,解除了接口和实现类直接的耦合性

发布了51 篇原创文章 · 获赞 28 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/weixin_44519467/article/details/105722883