@Component
public class HibernateTemplate {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
@Resource(name="sessionFactory") //此处静态方法使用注解会异常
public static void setSessionFactory(org.hibernate.SessionFactory sessionFactory) {
HibernateTemplate.sessionFactory = sessionFactory;
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
session = (sessionFactory != null) ? sessionFactory.getCurrentSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
}
使用注解方法注入sessionFactory出现异常:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in class path resource [applicationContext.xml]: Post-processing failed of bean type [class com.util.HibernateTemplate] failed; nested exception is java.lang.IllegalStateException:
@Resource annotation is not supported on static methods
解决方法:
去掉注解,换成在applicationContext.xml中注入hibernateTemplate。
<bean id="hibernateTemplate" class="com.util.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
或者将sesSessionFactory方法改为非静态
然后可以从baseDao使用注解方式注入hibernateTemplate
private HibernateTemplate template;
public HibernateTemplate getTemplate() {
return template;
}
@Resource(name="hibernateTemplate")
public void setTemplate(HibernateTemplate template) {
this.template = template;
}