Spring 4 + Hibernate 4 非法参数异常:属性"会话工厂"是必需的



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

下面是包含数据源和持久性异常转换处理器配置的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;
    }   
}

然后这里是包含休眠配置的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());

似乎春天无法实例化会话工厂豆,但我不知道可能是什么问题......

对此,你怎么看?

谢谢

你忘了打电话

lsfb.afterPropertiesSet()

在从lsfb获取对象之前。 afterPropertiesSet()是生成和公开会话工厂的方法。

解决此问题的一种方法是,您正在为sessionFactory使用构造函数注入,该Factory不能很好地处理注释公开的bean。(不确定Spring 4如何对此做出任何改进。我只使用了 Spring 3.5 及更低版本(

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

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

所以注释可以得到豆子。

正如 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 方法以创建事务管理器。

相关内容

  • 没有找到相关文章

最新更新