Spring ApplicationContext容器

应用程序上下文(Application Context)是Spring更先进的容器。以它的BeanFactory类似可以加载bean定义,并根据要求分配bean。此外,它增加了更多的企业特定的功能,例如从一个属性文件解析文本消息的能力,并发布应用程序事件感兴趣的事件监听器的能力。此容器是由org.springframework.context.ApplicationContext 接口定义。

ApplicationContext 包括了 BeanFactory 所有的功能,因此通常建议在 BeanFactory。 BeanFactory中仍然可以用于重量轻的应用,如移动装置或基于小应用程序的应用程序。

最常用的 ApplicationContext 实现是:

  • FileSystemXmlApplicationContext: 这个容器加载从一个XML文件中的bean的定义。在这里,你需要提供给构造函数中的XML bean配置文件的完整路径。

  • ClassPathXmlApplicationContext 这个容器加载从一个XML文件中的bean的定义。在这里,您不需要提供XML文件的完整路径,但你需要正确设置CLASSPATH,因为这个容器会看在CLASSPATH中bean的XML配置文件.

  • WebXmlApplicationContext: 此容器加载所有的bean从Web应用程序中定义的XML文件。

我们已经看到在Spring 的Hello World示例ClassPathXmlApplicationContext容器的例子,我们将更多地谈论XmlWebApplicationContext 在一个单独的章节时,我们将讨论基于Web的Spring应用程序。所以,让我们看到FileSystemXmlApplicationContext一个例子。

例子:

我们使用Eclipse IDE,然后按照下面的步骤来创建一个 Spring 应用程序:

步骤 描述
1 Create a project with a name SpringExample and create a package com.manongjc under the src folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.manongjc package.
4 Create Beans configuration file Beans.xml under the src folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

这里是HelloWorld.java 文件的内容:

package com.manongjc;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }

   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

下面是第二个文件MainApp.java 的内容:

package com.manongjc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {

      ApplicationContext context = new FileSystemXmlApplicationContext
            ("C:/Users/ZARA/workspace/HelloSpring/src/Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
   }
}

有以下两个要点需要注意在主要程序中:

  1. 第一步是创建工厂对象,我们使用的框架API的 FileSystemXmlApplicationContext来从给定的路径加载bean配置文件之后,创建工厂bean。API的FileSystemXmlApplicationContext()需要创建和初始化所有的对象。在XML bean配置文件中提到的bean类。

  2. 第二个步骤是用来使用创建的上下文的getBean()方法获得所需的bean。此方法使用bean的id返回,最终可以构造到实际对象的通用对象。一旦有了对象,我们就可以使用这个对象调用任何类方法。

以下是bean配置文件beans.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-3.0.xsd">

   <bean id="helloWorld" class="com.manongjc.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>

一旦创建源代码和bean配置文件完成,让我们运行应用程序。如果一切顺利,这将打印以下信息:

Your Message : Hello World!