<pre class="plain" name="code">1、实现ApplicationContextAware接口的setApplicationContext方法,Spring在加载的时候,调用这个方法,把ApplicationContext对象实例化
/**
* Copyright (c) 2005-2009 google.com
*
* Licensed under google;
*
* $Id: SpringContextHolder.java 763 2009-12-27 18:36:21Z by google $
*/
package com.xwtech.ext.service;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
*
* @author majingang 2382
* @see [相关类/方法]
*/
public class SpringContextHolder implements ApplicationContextAware{
/**
* 日志对象
*/
private static final Logger logger = Logger.getLogger(SpringContextHolder.class);
public static ApplicationContext applicationContext;
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return applicationContext;
}
/**
* 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
checkApplicationContext();
return (T) applicationContext.getBean(name);
}
/**
* 返回当前的bean的ID是否存在容器中
* @param cmd String Spring容器bean的ID
* @return
*/
public static boolean containsLocalBean(String cmd)
{
checkApplicationContext();
return applicationContext.containsLocalBean(cmd);
}
/**
* 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<T> clazz) {
checkApplicationContext();
return (T) applicationContext.getBeansOfType(clazz);
}
private static void checkApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
}
}
/**
* 设置ApplicationContext对象
* @param context ApplicationContext
* @throws BeansException
*/
public void setApplicationContext(ApplicationContext context) throws BeansException
{
logger.info("setApplicationContext =" + context.getApplicationName());
SpringContextHolder.applicationContext = context;
}
}
2、在Spring的xml文件中配置
<bean class="com.xwtech.ext.service.SpringContextHolder" lazy-init="false"/>
注意:lazy-init="false"加上
3、Spring版本
版本号:3.2.2
问题描述:
已经启动了服务,通过main方法测试,发现ApplicationContext对象为null。
思路:通过debug模式调试,发现这个对象在容器加载的时候,已经实例化了。后来同事帮忙,不在同一个进程中。
解决办法:通过http方式调用,可以查询到对象。