Spring 4 + Hibernate 4 IllegalArgumentException:Property' sessionFactory'是必须的

时间:2014-04-09 11:18:56

标签: java hibernate spring-data illegalargumentexception sessionfactory

我正在使用Spring Data和Hibernate编写DAL但是我遇到了IllegalArgumentException异常,这个异常停止了我的工作。

这是包含DataSource和持久性异常转换处理器配置的DALConf.java

package my.dal.config;

import java.util.Properties;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;


@Configuration
@ComponentScan(basePackages = { "my.dal" })
@PropertySource("classpath:dbconnection.properties")
public class DALConfig {

    private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";  
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";  
    private static final String PROPERTY_NAME_DATABASE_URL = "db.url";  
    private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";  
    private static final String PROPERTY_NAME_POOL_INITIAL_SIZE = "pool.initialsize";
    private static final String PROPERTY_NAME_POOL_MAX_IDLE = "pool.maxidle";

    @Resource
    private Environment environment;   

    @Bean
    public DataSource dataSource() throws Exception
    {
        Properties props = new Properties();

        props.put("driverClassName", environment.getProperty(PROPERTY_NAME_DATABASE_DRIVER));
        props.put("url", environment.getProperty(PROPERTY_NAME_DATABASE_URL));
        props.put("username", environment.getProperty(PROPERTY_NAME_DATABASE_USERNAME));
        props.put("password", environment.getProperty(PROPERTY_NAME_DATABASE_PASSWORD));
        props.put("initialSize", environment.getProperty(PROPERTY_NAME_POOL_INITIAL_SIZE));
        props.put("maxIdle", environment.getProperty(PROPERTY_NAME_POOL_MAX_IDLE));

        BasicDataSource bds = BasicDataSourceFactory.createDataSource(props);

        return bds; 
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor()
    {
        PersistenceExceptionTranslationPostProcessor b = new PersistenceExceptionTranslationPostProcessor();
        return b;
    }   
}

然后这里是包含Hibernate配置的HibernateConfig.class

package my.dal.config;

import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ComponentScan(basePackages = { "my.dal" })
@PropertySource("classpath:hibernate.properties")
@EnableTransactionManagement
public class HibernateConfig {

    private static final String PROPERTY_NAME_DAL_CLASSES_PACKAGE = "hibernate.dal.package";  
    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.showsql";

    @Resource
    private Environment environment;  

    @Autowired
    DataSource dataSource;

    @Bean
    public SessionFactory sessionFactory()
    {

        LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();

        lsfb.setPackagesToScan(environment.getProperty(PROPERTY_NAME_DAL_CLASSES_PACKAGE));

        Properties hibernateProperties = new Properties();
        hibernateProperties.put("dialect", environment.getProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        hibernateProperties.put("show_sql", environment.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

        lsfb.setHibernateProperties(hibernateProperties);
        lsfb.setDataSource(dataSource);
        return lsfb.getObject();

    }

    @Bean 
    public HibernateExceptionTranslator hibernateExceptionTranslator(){ 
      return new HibernateExceptionTranslator(); 
    }


    @Bean
    public HibernateTransactionManager transactionManager()
    {
        // HERE THE EXCEPTION IS THROWN
        HibernateTransactionManager htm = new HibernateTransactionManager(sessionFactory());
        return htm;
    }   

}

这是DAO UserDAO.java

package my.dal.dao;

import my.models.dal.User;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;


@Repository
public class UserDAO
{

    private SessionFactory sessionFactory;

    @Autowired
    public UserDAO(SessionFactory sessionFactory) {
        this.sessionFactory=sessionFactory;
    }

    @Transactional
    public int insert(User user) {
        return (Integer) sessionFactory.getCurrentSession().save(user);
    }

    @Transactional
    public User getByUsername(String username) {
        return (User) sessionFactory.getCurrentSession().get(User.class, username);
    }

    @Transactional
    public void update(User user) {
        sessionFactory.getCurrentSession().merge(user);
    }

    @Transactional
    public void delete(String username) {
        User u = getByUsername(username);
        sessionFactory.getCurrentSession().delete(u);
    }

}

最后,这是测试类DALTest.java

package my.dal.tests;

import static org.junit.Assert.assertTrue;
import my.dal.config.DALConfig;
import my.dal.config.HibernateConfig;
import my.dal.dao.UserDAO;
import my.models.dal.User;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(classes = { DALConfig.class, HibernateConfig.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class DALTest {

    @Autowired
    SessionFactory sessionFactory;

    @Test
    public void testGetUser() {
        UserDAO userDAO = new UserDAO(sessionFactory);
        User user = null;
        user = userDAO.getByUsername("mrossi");

        assertTrue(null != user);
    }

}

测试的执行以以下异常结束

...
Caused by: java.lang.IllegalArgumentException: Property 'sessionFactory' is required
    at org.springframework.orm.hibernate4.HibernateTransactionManager.afterPropertiesSet(HibernateTransactionManager.java:247)
    at org.springframework.orm.hibernate4.HibernateTransactionManager.<init>(HibernateTransactionManager.java:130)
    at my.dal.config.HibernateConfig.transactionManager(HibernateConfig.java:66)
...

在这一行被抛出

HibernateTransactionManager htm = new HibernateTransactionManager(sessionFactory());

看起来Spring无法实例化sessionFactory bean,但我不知道会出现什么问题......

你怎么看?

谢谢

3 个答案:

答案 0 :(得分:7)

你忘了打电话了

lsfb.afterPropertiesSet()

lsfb获取对象之前。 afterPropertiesSet()是构建和公开会话工厂的方法。

答案 1 :(得分:1)

解决这个问题的一种方法是你使用构造函数注入来处理sessionFactory,它不能很好地处理注释暴露的bean。 (不确定Spring 4如何对此做出任何改进。我只使用Spring 3.5及以下版本)

我建议在UserDAO.java中使用getter / setter方法注入

private SessionFactory  sessionFactory;

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

因此注释可以获得bean。

答案 2 :(得分:1)

正如JB Nizet建议的那样,如果您自己处理对象生命周期,那么您将错过对afterPropertiesSet()的调用。我想提出一个稍好的配置版本来避免这个问题,在其他情况下你可能会遇到这个问题。

每当在JavaConfig中配置FactoryBean时,返回工厂并引用要在客户端方法上生成的实际对象。在您的示例中,这看起来像这样:

@Configuration
class YourConfig {

  @Bean
  public LocalSessionFactoryBean sessionFactory() {
    // setup factory
  }

  @Bean
  public HibernateTransactionManager transactionManager(SessionFactory factory) {
    return new HibernateTransactionManager(factory);
  }
}

如您所见,我们不会在工厂上手动调用任何生命周期回调,因为我们必须按原样返回它。春天会为我们做到这一点。它还会在其上调用….getObject()来创建实际的SessionFactory并将其移交到@Bean方法中以创建事务管理器。