When I was using Hibernate I had a configuration class like this:
@Configuration
@ComponentScan
public class HibernateConfiguration {
@Bean
public LocalSessionFactoryBean sessionFactory() {
return new LocalSessionFactoryBean();
}
}
Then I want to make sure this configuration class works fine, so I wrote an unit test like below:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = HibernateConfiguration.class)
public class HibernateConfigurationTest {
@Autowired
private LocalSessionFactoryBean localSessionFactoryBean;
@Test
public void someTest(){
}
}
Then Intellij keeps telling me this message, and it also fail the compile so it's not an Intellij bug:
Could not autowire. No beans of
LocalSessionFactoryBean
type found.
And after I changed the LocalSessionFactoryBean
to SessionFactory
it works fine.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = HibernateConfiguration.class)
public class HibernateConfigurationTest {
@Autowired
private SessionFactory localSessionFactoryBean;
@Test
public void someTest(){
}
}
And below is the source code of LocalSessionFactoryBean
:
public class LocalSessionFactoryBean extends HibernateExceptionTranslator
implements FactoryBean<SessionFactory>, ResourceLoaderAware, InitializingBean, DisposableBean {
}
Below are some version information:
<properties>
<springframework.version>4.0.6.RELEASE</springframework.version>
<hibernate.version>4.3.6.Final</hibernate.version>
<mysql.version>5.1.31</mysql.version>
<joda-time.version>2.3</joda-time.version>
<testng.version>6.9.4</testng.version>
<mockito.version>1.10.19</mockito.version>
<h2.version>1.4.187</h2.version>
<dbunit.version>2.2</dbunit.version>
</properties>
So why Spring could not autowire when I was using LocalSessionFactoryBean
? I think I have some misunderstand about the type deduction of Spring bean, because in my opinion the method below @Bean
in the configuration class will register a bean which type is LocalSessionFactoryBean
, rather than SessionFactory
, and then the autowired should works fine but it didn't. Can anyone please give me some learning material about that? I tried to search something like that and got very little useful result. With many thanks!
您需要注入SqlSessionFactory而不是SessionFactory。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.