《Spring In Action》学习笔记(二):Spring Container

在一个Spring-based application中,程序中的对象都生存在Spring Container中。由这一Container来负责这些对象的生成、关联、配置和管理等等。

两类容器

在Spring中,存在多个容器的实现,大体可以分为两大类:

  • Bean factories
    • 由接口org.springframework.beans.factory.BeanFactory定义
    • 最简单的容器,为DI提供基本的支持
  • Application contexts
    • 由接口org.springframework.context.ApplicationContext定义
      - 建立在bean factory基础上,提供application-framework services

在实际应用中,由于bean factories过于底层,不便于应用。所以,在大部分程序中,一般更倾向于采用application contexts

Application Context 容器

常见的一些application contexts

  • AnnotationConfigApplicationContext:Loads a Spring application context from one or more Java-based configuration classes
  • AnnotationConfigWebApplicationContext:Loads a Spring web application context from one or more Java-based configuration classes
  • ClassPathXmlApplicationContext:Loads a context definition from one ormore XML files located in the classpath, treating context-definition files as classpath
    resources
  • FileSystemXmlApplicationContext:Loads a context definition from one or more XML files in the filesystem
  • XmlWebApplicationContext:Loads context definitions from one or more XML files contained in a web application

两个例子:

1
2
ApplicationContext context = new FileSystemXmlApplicationContext("c:/knight.xml");
ApplicationContext context = new ClassPathXmlApplicationContext("knight.xml");