zoukankan      html  css  js  c++  java
  • Spring核心技术之IOC容器(一):IOC容器与Bean简介

    最近开始研究Spring框架,今天学习Spring的核心内容IOC 与 Bean

    1. Spring IOC 与 Bean 简介

       Inversion of Control (IoC)即控制反转,也叫dependency injection (DI)依赖注入,Spring实现了一个基于配置文件的复杂工厂模式来提供实现控制反转。

       org.springframework.beans 和org.springframework.context包是Spring中实现IOC的基础包,其中BeanFactory接口提供一套基于配置文件来管理对象类型的机制,ApplicationContext接口继承自BeanFactory接口,除了包含BeanFactory的所有功能之外,在国际化支持、资源访问(如URL和文件)、事件传播等方面进行了良好的支持,而WebApplicationContext是专门针对Web应用。

      由Spring IOC管理、实例化、组装的应用程序对象,称为Bean,Bean与Bean之间的依赖关系存放于Spring配置元数据中。

    2. Spring IOC容器

      org.springframework.context.ApplicationContex接口代表IOC容器,根据配置元数据来实现Bean的初始化、配置和装配,配置数据可以是XMl格式、Java注解格式或者Java代码格式。

      常见的实现ApplicationContext接口的类是ClassPathXMLApplicationContext和FileSystemXmlApplicationContext。

    2.1 Spring IOC 配置实例

      根据配置文件创建ApplicationContext:

    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

      services.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
               http://www.springframework.org/schema/beans/spring-beans.xsd">
    
      <!-- services -->
    
      <bean id="petStore"
            class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
        <property name="accountDao" ref="accountDao"/>
        <property name="itemDao" ref="itemDao"/>
        <!-- additional collaborators and configuration for this bean go here -->
      </bean>
    
      <!-- more bean definitions for services go here -->
    
    </beans>

      daos.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
               http://www.springframework.org/schema/beans/spring-beans.xsd">
    
      <bean id="accountDao"
          class="org.springframework.samples.jpetstore.dao.ibatis.SqlMapAccountDao">
        <!-- additional collaborators and configuration for this bean go here -->
      </bean>
    
      <bean id="itemDao" class="org.springframework.samples.jpetstore.dao.ibatis.SqlMapItemDao">
        <!-- additional collaborators and configuration for this bean go here -->
      </bean>
    
      <!-- more bean definitions for data access objects go here -->
    
    </beans>

      也可以用<import>标签把多个配置文件引用到一个配置文件中,如下

    <beans>
    
        <import resource="services.xml"/>
        <import resource="resources/messageSource.xml"/>
        <import resource="/resources/themeSource.xml"/>
    
        <bean id="bean1" class="..."/>
        <bean id="bean2" class="..."/>
    
    </beans>

    2.2.使用IOC容器创建对象

      使用ApplicationContext接口中的 T getBean(String name, Class<T> requiredType)方法可以创建你想要的对象实例

    // create and configure beans
    ApplicationContext context =
        new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
    
    // retrieve configured instance
    PetStoreServiceImpl service = context.getBean("petStore", PetStoreServiceImpl.class);
    
    // use configured instance
    List userList = service.getUsernameList();

      事实上,我们的应用应该不要直接调用getBean方法,因此可以完全不依赖于Sping的API,比如Spring和Web集成框架可以直接将对象注入到web框架的Controller中。

    3.Bean 

      Spring IOC容器管理着很多的Bean,这些Bean是根据配置数据而创建的,但是对于Spring IOC容器本身来说,这些Bean的配置数据最终使用BeanDefinition对象来表示,一个BeanDefinition包含如下一些数据:bean对应的类的完全限定名、Bean的行为(范围、生命周期等)、与其他Bean的依赖关系、其他配置信息。

      Spring也允许手动加载外部对象,通过ApplicationContext的getBeanFactory方法获取DefaultListableBeanFactory, 然后通过DefaultListableBeanFactory中的registerSingleton(...)或registerBeanDefinition(...)方法加载外部的对象。

      每个Bean通常有一个标识符,所有的标识符在同一个容器内不能重复,xml配置中,可以用id或name类标识一个bean,id属性只能设置一个确定的标识,而name属性中可以有多个标识符,用逗号分好或空格隔开。你也可以不填id或name,那么容器会自动生成一个标识符给bean。有时候,各个子系统希望用不同的名字访问同一个bean,那么你也可以使用<alias>标签在bean的外部为他取一个别名,格式如下:

    <alias name="subsystemA-dataSource" alias="subsystemB-dataSource"/>
    <alias name="subsystemA-dataSource" alias="myApp-dataSource" />

      Spring可以管理任何形式的Bean,不一定非要是标准的JavaBean。class属性用来指定bean对应的class,如下:

    <bean id="exampleBean" class="examples.ExampleBean"/>
    <bean name="anotherExample" class="examples.ExampleBeanTwo"/>

    3.1根据静态工厂方法来创建bean

      如果你的bean需要根据特定的静态工厂方法来创建,那么你可以这样配置,其中class值的工厂方法所在的class,而不是工厂方法返回值的class,factory-method指定静态工厂方法名

    <bean id="clientService" class="examples.ClientService"  factory-method="createInstance"/>
    public class ClientService {
      private static ClientService clientService = new ClientService();
      private ClientService() {}
      public static ClientService createInstance() {
        return clientService;
      }
    }

    3.2根据实例工厂方法来创建bean

    根据实例工厂方法创建bean的配置,它根据另一个bean来创建工厂方法对应的实例,使用factory-bean属性来指定工厂方法所在的bean的名称,如下:

    <!-- the factory bean, which contains a method called createInstance() -->
    <bean id="serviceLocator" class="examples.DefaultServiceLocator">
      <!-- inject any dependencies required by this locator bean -->
    </bean>
    <!-- the bean to be created via the factory bean -->
    <bean id="clientService"
          factory-bean="serviceLocator"
          factory-method="createClientServiceInstance"/>
    public class DefaultServiceLocator {
      private static ClientService clientService = new ClientServiceImpl();
      private DefaultServiceLocator() {}
      public ClientService createClientServiceInstance() {
        return clientService;
      }
    }
  • 相关阅读:
    GitCam一款Gif动画制作软件
    IniParse解析类
    一个网页设计师应该考虑的9件事
    Backit轻松为您的网站创建备份
    [翻译]Web开发牛人访谈:你们都在用什么?
    简单文件服务器
    一个网站访问速度测试工具
    GS运维常用工具及文档
    Oracle快速收集AWR的方案
    Oracle调整内存参后报ORA-00844和ORA-00851
  • 原文地址:https://www.cnblogs.com/ArtofDesign/p/5605442.html
Copyright © 2011-2022 走看看