![](/img/trans.png)
[英]Java Spring Boot: Consider defining a bean named 'entityManagerFactory' in your configuration
[英]Spring boot inject EntityManagerFactory in configuration class
我正在使用Spring Boot,並且我想將Spring與Hibernate集成在一起。 我想制作一個Session Factory bean以便進一步使用。 但是我不能自動裝配EntityManagerFactory,我不能僅在配置類中自動裝配它,在其他類中也可以工作。 你能幫忙嗎?
配置類
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>
當你說
但是我不能自動連接EntityManagerFactory
是否在運行時無法編譯或引發異常? 如果是后者,那么堆棧跟蹤說明了什么?
一種可能的解決方案/解決方法是使用@PersistenceContext
批注將em注入配置中,而不是em工廠:
@Configuration
@EnableTransactionManagement
public class DatabaseConfiguration {
@PersistenceContext
private EntityManager entityManager;
@Bean
public SessionFactory getSessionFactory() {
// no need to check for null here because if the unwrap fails, it will do
// so by throwing a PersistenceException rather than returning null.
return entityManager.unwrap( Session.class ).getFactory();
}
}
我不確定為什么要同時公開兩個bean,因為@chrylis指出,可以在需要的地方輕松將EMF解包為SF。
// 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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.