通过ApplicationContextAware加载Spring上下文环境

项目用到了ApplicationContextAware,通过它Spring容器会自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法。

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

使用方法如下:

1.实现ApplicationContextAware接口:

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 {
		context = applicationContext;
	}
	
	public static Object getBean(String name){
		return context.getBean(name);
	}
	
}


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



	
	
	
	


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


	
		org.springframework.web.context.ContextLoaderListener
	


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

你可能感兴趣的:(Spring)