天天看点

Spring基于XML的IoC环境搭建

1.什么是IoC

    IoC,即控制反转(Inversion of Control),把创建对象的权利交给框架,是框架的重要特征。它包括依赖注入和依赖查找。

2.IoC的作用

    削减计算机程序的耦合,即削减代码之间的依赖关系。

3.基于XML的配置

3.1拷贝必备的jar包到工程的lib目录中

Spring基于XML的IoC环境搭建

3.2在类的根路径下创建一个任意名称的xml文件(不能是中文)

Spring基于XML的IoC环境搭建

给配置文件导入约束:

/spring-framework-5.0.2.RELEASE/docs/spring-framework-reference/html5/core.html 
           
<?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> 
           

3.3让spring管理资源,在配置文件中配置service和dao

<!-- bean 标签:用于配置让 spring 创建对象,并且存入 ioc 容器之中       
        id 属性:对象的唯一标识。       
        class 属性:指定要创建对象的全限定类名 
--> 
<!-- 配置 service -->    
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"> 
</bean> 
<!-- 配置 dao --> 
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
</bean> 
           

3.4测试配置是否成功

public class Client {  
    /** 
      * 使用 main 方法获取容器测试执行 
     */  
    public static void main(String[] args) {   
    //1.使用 ApplicationContext 接口,就是在获取 spring 容器   
    ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");   
    //2.根据 bean 的 id 获取对象   
    IAccountService aService = (IAccountService) ac.getBean("accountService");   
    System.out.println(aService);   
 
    IAccountDao aDao = (IAccountDao) ac.getBean("accountDao");       
    System.out.println(aDao);  
    } 
} 
           

运行结果:

Spring基于XML的IoC环境搭建