最近要改造一下项目,自动扫描注册service和dao,自动注入dao、service;但遇到No Session found for current thread 的问题,配置如下:
*************spring配置文件:*************
<!-- 自动注册bean -->
<context:component-scan base-package="mod" use-default-filters="true"> <context:include-filter type="regex" expression="mod.dao.*" /> <context:include-filter type="regex" expression="mod.service.*" /> </context:component-scan>
<!-- 注册HibernateDAO -->
<bean class="com.base.HibernateDAO" scope="prototype">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
//bean 只配置了action的(这个是必须的)
<bean id="admin_log_Action" class="mod.action.sys.LogAction" scope="prototype" />
同时配置了声明式事务(为了方便,无需在Service里加注解)
*************dao层(没有接口,直接继承Hibernate原生泛型DAO):*************
@Repository
public class LogDAO extends HibernateDAO<Log> {
}
*************Service层(接口+实现类):*************
@Service
public interface LogService {}
@Service
public class LogServiceImpl implements LogService {}
*************action层:*************
public class LogAction extends AbstractAction {
private static final long serialVersionUID = 1L;
@Resource
private LogService logService;
}
*************HibernateDAO基类(无接口)*************
public class HibernateDAO<T> {
protected Logger logger = LoggerFactory.getLogger(getClass());
protected SessionFactory sessionFactory;
protected Class<T> entityClass;
public HibernateDAO() {
this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass()); }
public HibernateDAO(final SessionFactory sessionFactory, final Class<T> entityClass) {
this.sessionFactory = sessionFactory; this.entityClass = entityClass; }
public SessionFactory getSessionFactory() { return sessionFactory; }
public void setSessionFactory(final SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory; }
public Session getSession() {
return sessionFactory.getCurrentSession(); } }
在setSessionFactory 上加 @Autowired 的时候,报出错误为:
org.hibernate.HibernateException: No Session found for current thread at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97) at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:881)
去掉的话报错为:
java.lang.NullPointerException at com.base.HibernateDAO.getSession(HibernateDAO.java:110) at com.base.HibernateDAO.createCriteria(HibernateDAO.java:359)
有木有大侠知道,这是什么问题啊?请指导一下啊:
你有在Hibernate主配置文件中设置
<property name="hibernate.current_session_context_class">thread</property>
这个属性?
空指针依然么,明显是属性没有注入,你调用了肯定空指针了。