Spring Boot在配置类中注入EntityManagerFactory [英] Spring boot inject EntityManagerFactory in configuration class
本文介绍了Spring Boot在配置类中注入EntityManagerFactory的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Spring Boot,并且我想将Spring与Hibernate集成在一起.我想制作一个Session Factory bean以便进一步使用.但是我不能自动装配EntityManagerFactory,我不能仅在配置类中自动装配它,在其他类中也可以工作.你能帮忙吗?
I'm using spring boot and i want to integrate spring with hibernate. I want to make a Session Factory bean for further using. But I can't autowire EntityManagerFactory, I can't autowire it only in the configuration class, in other classes it works. Can you help, please?
配置类
package kz.training.springrest.configuration;
@Configuration
@EnableTransactionManagement
public class DatabaseConfiguration {
@Autowired
private EntityManagerFactory entityManagerFactory;
@Bean
public SessionFactory getSessionFactory() {
if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
throw new NullPointerException("factory is not a hibernate factory");
}
return entityManagerFactory.unwrap(SessionFactory.class);
}
}
依赖项
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.2</version>
</dependency
</dependencies>
推荐答案
我不确定为什么要同时公开两个bean,因为@chrylis指出,您可以在需要的地方轻松将EMF解包为SF.
I'm not exactly sure why you want to expose both beans because as @chrylis points out, you can easily unwrap the EMF into a SF where needed.
// Some spring component
@Component
public class MyFancyComponent {
@PersistenceContext
private EntityManager entityManager;
public void doSomethingFancy() {
// public SessionFactory API
final SessionFactory sf = entityManager
.unwrap( Session.class ).getFactory();
// public SessionFactoryImplementor SPI
final SessionFactoryImplementor sfi = entityManager
.unwrap( SessionImplementor.class ).getFactory();
}
}
这篇关于Spring Boot在配置类中注入EntityManagerFactory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文