通过ApplicationContextAware加载Spring上下文环境

    xiaoxiao2026-02-15  19

    在程序中每一次使用new ClassPathXmlApplicationContext时都会重新装载配置文件并实例化上下文bean。此时如果某些线程类也配置在该文件中,那么会造成做相同工作的线程被启动多次(包括web容器初始化时启动的以及new ClasspathXmlApplicationContext时启动的线程)。为了避免这种情况就需要用到ApplicationContextAware,通过它Spring容器会自动调用ApplicationContextAware接口中的setApplicationContext方法将把上下文环境对象注入进去

    我们在ApplicationContextAware的实现类中,就可以通过这个上下文环境对象得到Spring容器中的Bean。

    具体如下:

    1.实现ApplicationContextAware接口:

    [java]  view plain copy package com.bis.majian.practice.module.spring.util;      import org.springframework.beans.BeansException;   import org.springframework.context.ApplicationContext;   import org.springframework.context.ApplicationContextAware;      public class SpringContextHelper implements ApplicationContextAware {       private static ApplicationContext context = null;          @Override       public void setApplicationContext(ApplicationContext applicationContext)               throws BeansException {           this.context = applicationContext;       }              public static Object getBean(String name){           return context.getBean(name);       }          }  

    2.在Spring的配置文件中配置这个类,Spring容器会在加载完Spring容器后把上下文对象调用这个对象中的setApplicationContext方法:

    [html]  view plain copy <?xml version="1.0" encoding="UTF-8"?>   <beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"       xmlns:context="http://www.springframework.org/schema/context"       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd        http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-autowire="byName">              <bean id="springContextHelper" class="com.bis.majian.practice.module.spring.util.SpringContextHelper"></bean>              <context:component-scan base-package="com.bis.majian.practice.module.*" />   </beans>  

    3.在web项目中的web.xml中配置加载Spring容器的Listener:

    [html]  view plain copy <!-- 初始化Spring容器,让Spring容器随Web应用的启动而自动启动 -->       <listener>           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>       </listener>  

    4.在项目中即可通过这个SpringContextHelper调用getBean()方法得到Spring容器中的对象了。

    相关资源:python入门教程(PDF版)
    最新回复(0)