Spring学习笔记1---IoC容器

容器概述

org.springframework.context.ApplicationContext接口代表Spring IoC容器,并负责实例化,配置和组装Bean。容器通过读取配置元数据来获取有关要实例化,配置和组装哪些对象的指令。配置元数据以XML,Java批注或Java代码表示。它使您能够表达组成应用程序的对象以及这些对象之间的丰富相互依赖关系。

ApplicationContextSpring提供了该接口的几种实现。在独立应用程序中,通常创建ClassPathXmlApplicationContext 或的实例 FileSystemXmlApplicationContext。尽管XML是定义配置元数据的传统格式,但是您可以通过提供少量XML配置来声明性地启用对这些其他元数据格式的支持,从而指示容器将Java注释或代码用作元数据格式。

在大多数应用场景中,不需要显式的用户代码来实例化一个Spring IoC容器的一个或多个实例。例如,在Web应用程序场景中,应用程序文件中的简单八行(约)样板Web描述符XML web.xml通常就足够了(请参阅Web应用程序的便捷ApplicationContext实例化)。如果使用 Spring Tool Suite(基于Eclipse的开发环境),则只需单击几次鼠标或击键即可轻松创建此样板配置。

下图显示了Spring的工作原理的高级视图。您的应用程序类与配置元数据结合在一起,以便在ApplicationContext创建和初始化之后,您便拥有了一个完全配置且可执行的系统或应用程序。

容器魔术

 
图1. Spring IoC容器

基于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">

    <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>


id属性是标识单个bean定义的字符串。

class属性定义bean的类型,并使用完全限定的类名。

实例化容器: 

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");


 基于 IOC理论推导那篇文章的代码

配置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">

    <bean id="mysqlImpl" class="com.qi.dao.UserDaoMysqlImpl"/>
    <bean id="oracleImpl" class="com.qi.dao.UserDaoOracleImpl"/>
    <bean id="USerServiceImpl" class="com.qi.Service.UserServiceImpl">

<!--        ref 引用Spring中创建好的对象-->
<!--        Value 具体的值,基本的数据类型-->
        <property name="userDao" ref="oracleImpl"/>

    </bean>

</beans>
import com.qi.Service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Mytest {
    public static void main(String[] args) {
        //获取Spring ApplicationContext;
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        //容器在手,天下我有
        UserServiceImpl uSerServiceImpl = (UserServiceImpl) context.getBean("USerServiceImpl");
        uSerServiceImpl.getUser();
    }
}

运行结果:

如果用户要修改文件,则只需要在beans.xml中将 <property name="userDao" ref="oracleImpl"/> 将ref的值修改即可.

要实现不同的操作 , 只需要在xml配置文件中进行修改 , 所谓的IoC,一句话搞定 : 对象由Spring 来创建 , 管理 , 装配 !

原文地址:https://www.cnblogs.com/zhahu/p/12333678.html