junit实现opensessionInView保持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);
	}
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;
	}

}
 

相关推荐