`
allenwei
  • 浏览: 87657 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

在Junit中实现类似OpenSessionInViewFilter保持session的功能

阅读更多
private SessionFactory sessionFactory;

      //重写setUp方法
	protected void setUp() throws Exception {
		super.setUp();
		sessionFactory = (SessionFactory) SpringContext.getInstance().getBean(
				"sessionFactory");//SpringContext是自己创建spring工具类

		Session s = sessionFactory.openSession();
		TransactionSynchronizationManager.bindResource(sessionFactory,
				new SessionHolder(s));

	}

	protected void tearDown() throws Exception {
		super.tearDown();
		SessionHolder holder = (SessionHolder) TransactionSynchronizationManager
				.getResource(sessionFactory);
		Session s = holder.getSession();
		try {
			s.flush();
		} catch (Throwable e) {
			e.printStackTrace();
		}

		TransactionSynchronizationManager.unbindResource(sessionFactory);
		SessionFactoryUtils.closeSession(s);
	}

  SpringContext.class

public class SpringContext {

	private static SpringContext m_instance;

	private static String[] contextFiles = new String[] { "applicationContext.xml" };

	private ApplicationContext ctx;

	public SpringContext() {
		ctx = new ClassPathXmlApplicationContext(contextFiles);
	}

	public SpringContext(String[] setting) {
		ctx = new ClassPathXmlApplicationContext(setting);
	}

	public synchronized static SpringContext getInstance() {
		if (m_instance == null) {
			m_instance = new SpringContext(contextFiles);
		}
		return m_instance;
	}

	public Object getBean(String beanId) {
		Object o = ctx.getBean(beanId);
		if (o instanceof TransactionProxyFactoryBean) {
			TransactionProxyFactoryBean factoryBean = (TransactionProxyFactoryBean) o;
			o = factoryBean.getObject();
		}
		return o;
	}

}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics