在使用SpringMVC的时候我们可能会需要直接获得ApplicationContext对象,这里总结了两种方式供大家参考,同时也作为自己的笔记记录一下。
第一种:继承WebApplicationObjectSupport
,这种方式比较简单,我们只需要编写一个普通的Java类使其继承WebApplicationObjectSupport
,然后交由Spring管理就好了。
package com.jianggujin.web.utils;
import org.springframework.web.context.support.WebApplicationObjectSupport;
public class SpringContextHolder extends WebApplicationObjectSupport
{
}
然后在spring的配置文件中添加:
<bean id="springContextHolder" class="com.jianggujin.web.utils.SpringContextHolder" />
最后我们只需要将其注入到需要使用的bean中就好可以了。
第二种:监听ServletContext属性值变化,SpringMVC在初始化的时候会将ApplicationContext对象添加进ServletContext。在FrameorkServlet
的initWebApplicationContext
方法中偶们可以看到相关实现。
if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
属性名的规则为:FrameorkServlet全限定类名+.CONTEXT.+servlet名称
,所以我们只需要编写监听器监听ServletContext属性值变化就可以获得ApplicationContext对象,因为在配置SpringMVC的时候,我们的servlet名称可能会改变,所以这里我采用直接监听属性值的方式来获取ApplicationContext对象。
package com.jianggujin.web;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import org.springframework.context.ApplicationContext;
import com.jianggujin.logging.HQLog;
import com.jianggujin.logging.HQLogFactory;
public class SpringApplicationContextListener implements ServletContextAttributeListener
{
private static ApplicationContext applicationContext;
private HQLog logger = HQLogFactory.getLog(getClass());
public void attributeAdded(ServletContextAttributeEvent scab)
{
if (scab.getValue() instanceof ApplicationContext)
{
SpringApplicationContextListener.applicationContext = (ApplicationContext) scab.getValue();
logger.debug("spring appilication context was inited.");
}
}
public void attributeRemoved(ServletContextAttributeEvent scab)
{
if (scab.getValue() instanceof ApplicationContext)
{
SpringApplicationContextListener.applicationContext = null;
logger.debug("spring appilication context was removed.");
}
}
public void attributeReplaced(ServletContextAttributeEvent scab)
{
if (scab.getValue() instanceof ApplicationContext)
{
SpringApplicationContextListener.applicationContext = (ApplicationContext) scab.getValue();
logger.debug("spring appilication context was replaced.");
}
}
public static ApplicationContext getApplicationContext()
{
return applicationContext;
}
}
以上两种方式都是我在实际开发中总结出来的,不足之处还望指正。