SpringMVC自动装配与'sessionFactory' or 'hibernateTemplate' is required

    在进行Spring零配置环境搭建的过程中,很多人会遇到这个问题'sessionFactory' or 'hibernateTemplate' is required。

下面我们从如下几点来排查这个问题出现的原因:

1.是否正确配置sessionFactory

name="sessionFactory" id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    name="dataSource" ref="dataSource" />
    
    name="mappingLocations">
        
            classpath*:/**/entity/*.hbm.xml
        
    
    
    name="hibernateProperties">
        
            key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect
            key="hibernate.connection.provider_class">example.util.DruidConnectionProvider
            
            key="hibernate.show_sql">true
            key="hibernate.format_sql">true
            key="hibernate.hbm2ddl.auto">update
            key="hibernate.autoReconnect">true
            
            key="hibernate.jdbc.batch_size">50
            key="hibernate.connection.autocommit">false
            key="hibernate.connection.release_mode">auto
            key="hibernate.bytecode.use_reflection_optimizer">false
            key="javax.persistence.validation.mode">none

        
    

2.如果你的dao继承了HibernateDaoSupport,那你要检查下,你有没有为HibernateDaoSupport注入sessionFactory

@Resource(name="sessionFactory")
public void setSessionFactoryOverride(SessionFactory sessionFactory)
{
    super.setSessionFactory(sessionFactory);
}

3.如果上述配置都没问题,你需要检查下你是否开启了Spring自动装配,如果没有开启,那么在注解的时候会注入一个空的sessionFactory,hibernate检查的时候就会报错了,在Spring配置文件中加入byName的方式注入bean后就可以正常的使用注解了。

xml version="1.0" encoding="UTF-8"?>
xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"
       default-autowire="byName" default-lazy-init="false">

你可能感兴趣的:(SpringMVC)