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;
  }
}
时间: 2024-08-24 10:15:19

Spring核心技术之IOC容器(一):IOC容器与Bean简介的相关文章

Spring核心技术IoC容器(八)

本文针对自动装载的一些注解进行描述. 基于注解的容器配置 @Required注解 @Required注解需要应用到Bean的属性的setter方法上面,如下面的例子: public class SimpleMovieLister { private MovieFinder movieFinder; @Required public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } //

Spring核心技术IoC容器(六)

前文已经描述了Bean的作用域,本文将描述Bean的一些生命周期作用,配置还有Bean的继承. 定制Bean 生命周期回调 开发者通过实现Spring的InitializeingBean和DisposableBean接口,就可以让容器来管理Bean的生命周期.容器会调用afterPropertiesSet()前和destroy()后才会允许Bean在初始化和销毁Bean的时候执行一些操作. JSR-250的@PostConstruct和@PreDestroy注解就是现代Spring应用生命周期回

Spring核心技术IoC容器(五)

前文概述了Spring的容器,Bean,以及依赖的一些信息,本文将描述一下Bean的作用域 Bean的作用域 当开发者定义Bean的时候,同时也会定义了具体如何创建Bean实例的步骤.这些步骤是很重要的,因为只有通过这些配置,开发者才能创建实例对象. 开发者不仅可以控制多种多样的依赖到Bean之中,也可以配置Bean的作用域.这种方法是非常强大而且弹性也非常好,开发者可以通过配置来指定对象的作用域,而不用在Java类层次上来配置.Bean可以配置多种作用域.Spring框架支持5中作用域,有三种

Spring核心技术IoC容器(四)

前面两篇文章描述了IoC容器中依赖的概念,包括依赖注入以及注入细节配置.本文将继续描述玩全部的依赖信息. 使用 depends-on 如果一个Bean是另一个Bean的依赖的话,通常来说这个Bean也就是另一个Bean的属性之一.多数情况下,开发者可以在配置XML元数据的时候使用<ref/>标签.然而,有时Bean之间的依赖关系不是直接关联的.比如:需要调用类的静态实例化器来出发,类似数据库驱动注册.depends-on属性会使明确的强迫依赖的Bean在引用之前就会初始化.下面的例子使用dep

Spring核心技术(一)——IoC容器和Bean简介

IoC容器和Bean简介 这章包括了Spring框架对于IoC规则的实现.Ioc也同DI(依赖注入).而对象是通过构造函数,工厂方法,或者一些Set方法来定义对象之间的依赖的.容器在创建这些Bean对象的时候同时就会注入这些依赖.这个过程是根本上的反转了,不再由Bean本身来控制实例化和定位依赖,而是通过服务定位来控制这个过程,也是IoC(控制反转)的由来. org.springframework.beans和org.springframework.context包是Spring框架IoC容器的

Spring核心技术IoC容器(七)

本文将讨论如何关于在Spring生命周期中扩展Spring中的Bean功能. 容器的扩展 通常来说,开发者不需要通过继承ApplicationContext来实现自己的子类扩展功能.但是Spring IoC容器确实可以通过实现接口来增加一些功能.下面将描述一下这些接口. 通过BeanPostProcessor定义Bean BeanPostProcessor接口定义了一些回调方法,开发者可以通过实现来自己的实例化逻辑,依赖解析逻辑等等.如果开发者只是想在Spring容器完成了实例化,配置以及初始化

Spring 核心技术IoC容器(二)

本文将继续前文,描述Spring IoC中的依赖处理. 依赖 一般的企业应用也不会只有一个对象(或者是Spring Bean).甚至最简单的应用都要有一些对象来协同工作来让终端用户看到一个完整的应用.下一部分将解释开发者从单独的定义Bean,到让这些对象在一个应用中协同工作. 依赖注入 依赖注入是一个让对象只通过构造参数,工厂方法的参数或者配置的属性来定义他们的依赖.这些依赖也是对象所需要协同工作的对象.容器在之后会在创建Bean的时候注入这些依赖.整个过程完全反转了Bean自己控制实例化或者,

Spring 核心技术 IoC容器(一)

IoC 容器 IoC容器和Bean简介 这章包括了Spring框架对于IoC规则的实现.Ioc也同DI(依赖注入).而对象是通过构造函数,工厂方法,或者一些Set方法来定义对象之间的依赖的.容器在创建这些Bean对象的时候同时就会注入这些依赖.这个过程是根本上的反转了,不再由Bean本身来控制实例化和定位依赖,而是通过服务定位来控制这个过程,也是IoC(控制反转)的由来. org.springframework.beans和org.springframework.context包是Spring框

Spring 核心技术IoC容器 (三)

本文将继续前文,针对依赖注入的细节进行描述 依赖注入细节 如前文所述,开发者可以通过定义Bean的依赖的来引用其他的Bean或者是一些值.Spring基于XML的配置元数据支持一些子元素<property/>以及<constructor-arg/>来达到这一目的. 内在值类型(Java Primitives类型,字符串等) 元素<property/>有value属性来以易读的形式配置一个属性或者构造参数.Spring的遍历就是用来讲这些字符串的值转换成指定的类型. &l