自由获得WebApplicationContext的方式。
package com.common;
import javax.servlet.ServletContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.ServletContextAware;
public class WebApplicationUtils implements ApplicationContextAware,ServletContextAware{
public static ApplicationContext applicationContext = null;
public static ServletContext servletContext = null;
private static SessionFactory factory;
private static Session session;
public static SessionFactory getFactory() {
factory = (SessionFactory)WebApplicationUtils.getApplicationContext().getBean("sessionFactory");
return factory;
}
public static Session getSession() {
session = getFactory().getCurrentSession();
return session;
}
public void setApplicationContext(ApplicationContext actx) throws BeansException {
if(WebApplicationUtils.applicationContext==null){
WebApplicationUtils.applicationContext = actx;
}
}
public void setServletContext(ServletContext sctx) {
if(WebApplicationUtils.servletContext==null){
WebApplicationUtils.servletContext=sctx;
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static ServletContext getServletContext() {
return servletContext;
}
}