java - 如何解决在 Hibernate4 中的 ServletContext 资源中创建名称为 'sessionFactory' 的 bean 时出错的问题

标签 java spring session tomcat spring-mvc

我在构建应用程序 war 时在我的应用程序中使用 Hibernate4 实现 Multi-Tenancy ,我在 tomcat 的 catalina 中遇到以下错误。

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: 
protected org.hibernate.SessionFactory com.boxco.blip.dao.BaseDao.sessionFactory; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Error    creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext-persistence.xml]: 
Invocation of init method failed; nested exception is java.lang.NullPointerException

这是我的应用程序-persistance.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="...">

<context:annotation-config />
<tx:annotation-driven />
<context:component-scan base-package="com.boxco.blip">
</context:component-scan>

<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName">
        <value>jdbc/blip</value>
    </property>
    <property name="resourceRef">
        <value>true</value>
    </property>
</bean>


<!-- Hibernate Session Factory  -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="annotatedClasses">
        <list>
    <value>com.boxco.blip.model.Address</value> 
        </list>
    </property>
    <property name="hibernateProperties">          
         <map>
            <entry key="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
            <entry key="hibernate.hbm2ddl.auto" value="validate" />
            <entry key="hibernate.show_sql" value="true" />
            <entry key="hibernate.connection.autocommit" value="false" />
            <entry key="hibernate.jdbc.batch_size" value="0" />
            <entry key="hibernate.connection.release_mode" value="after_transaction" />
            <entry key="hibernate.multiTenancy" value="SCHEMA" />
            <entry key="hibernate.tenant_identifier_resolver" value-ref="multiTenantIdentifierResolver1" />
            <entry key="hibernate.multi_tenant_connection_provider" value-ref="multiTenantConnectionProvider1" />      
      </map>
    </property>
</bean>

 <bean id="multiTenantConnectionProvider1" class="com.boxco.blip.web.util.SchemaMultiTenantConnectionProviderBlip">
    <property name="dataSource" ref="dataSource"/>
  </bean>
 <bean id="multiTenantIdentifierResolver1" class="com.boxco.blip.web.util.SchemaCurrentTenantIdentifierResolverBlip" />

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
    <property name="dataSource" ref="dataSource"/>
</bean>    

我的 AddressDao.java 文件

package com.boxco.blip.dao;

import com.boxco.blip.model.Address;

public interface AddressDao {
   public Address getAddressByAddressId(int addressId);
 }

我的 AddressDaoImpl.java 文件

package com.boxco.blip.dao;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.boxco.blip.model.Address;
@Component
@Repository(value = "addressDao")

public class AddressDaoImpl extends BaseDao implements AddressDao {
private static final Logger logger = Logger.getLogger(AddressDaoImpl.class);

    @Override
 public Address getAddressByAddressId(int addressId) {
    logger.info("Entering getAddressByAddressId()........");
    Address address = null;
    Criteria criteria = getSession().createCriteria(Address.class);
    criteria.add(Restrictions.eq("addressId", addressId));
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    address = (Address)criteria.uniqueResult();
    logger.info("Exiting getAddressByAddressId()..........");
    return address;
}

我初始化 sessionFactory 对象的 Base Dao 文件:

package com.boxco.blip.dao;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.mysql.jdbc.Connection;

public abstract class BaseDao 
 {

@Autowired
@Qualifier("sessionFactory")
protected SessionFactory sessionFactory;

protected void init(SessionFactory factory) {
    try {
        setSessionFactory(factory);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public SessionFactory getSessionFactory() {
    return sessionFactory;
}

public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

public Session getSession() throws HibernateException {
    // return sessionFactory.getCurrentSession();
    return sessionFactory.withOptions().tenantIdentifier("BLIP1314ERP")
            .openSession();
}

     //some more methods
  }

我添加的Dispatcher-servlet.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="...">

<mvc:annotation-driven/>

<context:component-scan base-package="com.boxco">
    <!-- <context:exclude-filter type="regex" expression="com.boxco.blip.dao.*" /> -->
</context:component-scan>

<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
    <property name="basenames" value="views"/>

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <value>messages,error_codes</value>
    </property>
</bean> 

<bean id="validatorFactory"
      class="org.springmodules.validation.commons.DefaultValidatorFactory">
    <property name="validationConfigLocations">
        <list>
            <value>/WEB-INF/validator-rules.xml</value>
            <value>/WEB-INF/validator.xml</value>
            <value>/WEB-INF/validatorFas.xml</value>
            <value>/WEB-INF/validatorFas-rules.xml</value>
        </list>
    </property>
</bean>

<bean id="validator" class="org.springmodules.validation.commons.DefaultBeanValidator">
    <property name="validatorFactory" ref="validatorFactory"/>
</bean>     

错误是在我的 SessionFactory 初始化中,但为什么它没有得到 init 是我的问题..? (我是第一次处理这个错误)..

任何建议表示赞赏。

最佳答案

这不应该是您的解决方案,无论如何@repository 上的@component 注释是无用的。您可以插入@repository(更适合异常翻译)或@component。

关于java - 如何解决在 Hibernate4 中的 ServletContext 资源中创建名称为 'sessionFactory' 的 bean 时出错的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22712827/

相关文章:

java - 定义 id 映射到表中非主列的 hibernate hbm 文件是否合适

java - 如何记录 Spring @RestController @RequestMapping 方法的所有请求和 header 信息?

java - 如何允许 JMS 使用端口 7676

php - 如果 URL 具有某些文件扩展名,RackSpace Cloud 会删除 $_SESSION

php - 为什么 Symfony2 建议避免使用 'legacy' php session ?

Javascript:从cookie中读出 session ID

java - 向派生类中的 onClickListener 添加功能

java - 使用谓词按字符串值对映射进行排序

java - Antlr 可以将嵌入式语法路由到单独的文件进行处理吗?

java - 可能性 : Web Application through Spring MVC/Webflow