自由获得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;
}
}
获取WebApplicationContext的方法

本文介绍了一种通过实现ApplicationContextAware和ServletContextAware接口来获取Spring上下文(WebApplicationContext)的方法。此外,还展示了如何从该上下文中获取SessionFactory及Session实例。
1528

被折叠的 条评论
为什么被折叠?



