最近项目中采用了springmvc框架作为控制层,关于如果在controller中获取spring容器中的bean实例,遇到了点问题。
很早以前的一个版本是有个静态工厂类加载了spring容器,具体代码如下:
private static BeanFactory beanFactory = null;
static{
beanFactory =new ClassPathXmlApplicationContext("spring.xml");
}
/**
* 获取Bean对象
* @param pBeanID
* @return
*/
public static Object getBean(String pBeanID) {
return beanFactory.getBean(pBeanID);
}
后来改用spring提供的ContextLoaderListener这一监听器,在WEB应用启动时初始化spring容器,具体在web.xml里配置如下:
<!-- 应用的Spring配置的加载 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/conf/spring.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
这个版本存在一个问题,我们项目中未在spring容器注册的类如果想调用容器中的bean实例,需要servletContext这一参数信息。
具体获取方法有两种:
ApplicationContext context= WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
两者的区别是:第一种方法失败会抛异常,第二种返回null不做处理。
如果是没有servletContext的场景,难道又得回到最初的方法,维护个静态容器工厂!!
当然是有更好的方案,一样还是通过web.xml的监听器实现,在应用启动时初始化加载容器,并把它保存到静态变量中,具体代码和配置如下:
web.xml:
<!-- 保存spring容器,为spring容器外的类提供容器获取接口 --> <listener> <listener-class>com.rb.obs.face.common.util.SpringContextListener</listener-class> </listener>
监听器实现:
package com.rb.obs.face.common.util;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class SpringContextListener implements ServletContextListener {
private static WebApplicationContext context;
public SpringContextListener() {
super();
}
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
context = WebApplicationContextUtils.getWebApplicationContext(sce
.getServletContext());
}
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
public static ApplicationContext getApplicationContext() {
return context;
}
}
获取容器:
ApplicationContext context = SpringContextListener.getApplicationContext()