Spring中基于xml的IOC解耦

IOC是什么

控制反转,顾名思义就是控制权发生反转,例如

IUserService service = new UserService();
 IUserService service= (IUserService) BeanFactory.getBean("UserService");

上面那一段控制权是new,就是完全自主控制引用那个dao,下面那个是把控制权交给BeanFactory,由BeanFactory通过后面的字符串配置。这种控制权的转移就叫控制反转。

IOC能做什么

削减计算机程序的耦合(解除我们代码中的依赖关系)。并且spring中的ioc只能解决程序之间的依赖关系。其他的都做不了

Spring中基于xml的IOC解耦

<?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">
</beans>

比如我们要解决这个里面service层和dao层的耦合,我们接下来的步骤是

第一步在Beans里面配置Bean

<?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">
    <!--把对象的创建交给spring进行管理-->
    <!--配置唯一标记和全限定类名-->
        <bean id="userService" class="Service.IMPL.UserService"></bean>
        <bean id="userDao" class="Dao.IMPL.UserDao"></bean>
</beans>

第二步就是读取配置文件,通过id来获取Bean

package ui;
import Service.IUserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * 模拟一个表现层,用于调用业务层
 */
public class Client {

    public static void main(String[] args) {
        //1.使用 ApplicationContext 接口,就是在获取 spring 容器
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据 bean 的 id 获取对象
        IUserService service = (IUserService) context.getBean("userService");
        service.save();
    }
}

结果运行通过

总结步骤

基于xml的IOC解耦的步骤是 1,创建配置文件,把要配置的beans交给Spring管理 2,使用一个对象去得到那个核心容器。这个容器是spring里面的,相当于工厂模式里面的Map容器,我们不用创建。 3,再根据配置文件的id获取bean对象。

经验分享 程序员 微信小程序 职场和发展