我使用的是Spring Boot 2.0.0.RC1(包括Spring Framework 5.0.3.RELEASE),Hibernate 5.2.12.Final,JPA 2.1 API 1.0.0.Final .
我上课了
package com.example;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.persistence.EntityManagerFactory;
@Configuration
public class BeanConfig {
@Autowired
EntityManagerFactory emf;
@Bean
public SessionFactory sessionFactory(@Qualifier("entityManagerFactory") EntityManagerFactory emf) {
return emf.unwrap(SessionFactory.class);
}
}
然后错误
Error
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method sessionFactory in com.example.BeanConfig required a bean of type 'javax.persistence.EntityManagerFactory' that could not be found.
Action:
Consider defining a bean of type 'javax.persistence.EntityManagerFactory' in your configuration.
Process finished with exit code 1
如何解决这个问题?
3 回答
您遇到的具体错误是由
@Qualifier
注释引起的; Spring正在寻找具有您提到的特定名称的Bean,而不是寻找EntityManagerFactory
类型的任何Bean . 只需删除注释即可 .但是,一旦你修复了它,并且因为你也在构造SessionFactory的方法中注入了Bean,Spring Boot将生成另一个与循环依赖相关的错误 . 为避免这种情况,只需从
sessionFactory
方法中完全删除参数,因为您已在Config类中注入了EntityManagerFactory
.此代码将起作用:
在
BeanConfig
中,您应该通过@PersistenceUnit
注入JPAEntityManager
,而不是@Autowired
.并删除
getSessionFactory
,因为Hibernate SessionFactory已在内部创建,您始终可以打开EntityManagerFactory
.像这样:
如果你包含这个:
您不必自动装配
Entity Manager
或提供Session Factory
bean .您只需要提供JpaRepository接口,例如:
其中
Actor
是JPA
实体类,Integer
是ID /主键,并在service
impl类中注入ActorDao
.