我正在使用java配置进行hibernate,spring示例。我的配置文件是这样的:
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "dto" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
工作正常。没问题,但是当我手动尝试为trasactionManager设置sessionfactory参数时,如下所示..
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory());
return txManager;
}
IDE显示 - The method setSessionFactory(SessionFactory) in the type HibernateTransactionManager is not applicable for the arguments (LocalSessionFactoryBean)
所以我创建了一个像下面这样的sessionFactory
@Bean
@Autowired
public SessionFactory sessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionFactory = new LocalSessionFactoryBuilder(dataSource);
sessionFactory.addProperties(hibernateProperties());
sessionFactory.scanPackages("dto");
return sessionFactory.buildSessionFactory();
}
并传递给trasactionManager它工作。
我的问题是,即使第一种方法中没有sessionFactory实例,spring如何自动装入sessionFactory对象?
请澄清..
答案 0 :(得分:2)
您需要将方法返回类型更改为:
这应该是这样的:
@Bean
@Autowired
public PlatformTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
@Bean
public SessionFactory sessionFactory() {
Properties properties = new Properties();
properties.setProperty("hibernate.show_sql", "true")
properties.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory")
properties.setProperty("hibernate.cache.use_query_cache", "true")
properties.setProperty("hibernate.cache.use_second_level_cache", "true")
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
return new LocalSessionFactoryBuilder(dataSource())
.scanPackages("dto")
.addProperties(properties)
.buildSessionFactory();
}