Ioc-控制反转的本质

发布时间 2023-06-20 03:00:17作者: guki

 

 

 控制反转是一种设计思想,依赖注入 (Dependency Injection,简称DI,DI 是 IoC 的一种实现方式。所谓依赖注入就是由 IoC 容器在运行期间,动态地将某种依赖关系注入到对象之中。所以 IoC 和 DI 是从不同的角度的描述的同一件事情,就是通过引入 IoC 容器,利用依赖注入的方式,实现对象之间的解耦

 

为什么要控制反转呢?  提升开发效率  提高模块化  便于单元测试

 

控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式,在spring中实现控制反转是Ioc容器,其实现方法是依赖注入。

 

spring的配置文件官网地址:容器概述 :: Spring 框架

一般要用spring的配置文件从官网直接取再进行修改即可。

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="..." class="...">  
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <!-- more bean definitions go here -->

</beans>

 

 

对象由spring创建

对象的属性由spring容器设置

beans.xml实现代码:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

<!--使用spring来创建对象,这些都称为bean类-->
    <bean id="hello" class="com.haoqi.pojo.Hello">
        <property name="string" value="Spring"></property>
    </bean>
</beans>

 

测试类Test.java的代码:

import com.haoqi.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        //获取spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //对象都被spring容器管理着,要用直接从里面取出来
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

测试类的Test.java的hello对象和配置文件beans.xml的bean的id是对应的!!!

 

通过改变beans.xml文件中bean标签的ref=" "来改变容器的对象

此时的beans.xml的代码为:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--使用spring来创建对象,这些都称为bean类-->
    <bean id="mysqlImpl" class="com.haoqi.dao.UserMysqlImpl">

    </bean>
    <bean id="oracleImpl" class="com.haoqi.dao.UserOracleImpl"></bean>
    <bean id="userServiceImpl" class="com.haoqi.service.UserServiceImpl">
<!--       -ref 引用spring容器中创建好的对象-->
        <property name="userDao" ref="oracleImpl"></property>
    </bean>
</beans>

 

 总结:所谓Ioc,对象由spring 创建、管理、装配!!!