Spring JPA (Hibernate) 没有符合条件的 bean 类型:javax.persistence.EntityManagerFactory
Posted
技术标签:
【中文标题】Spring JPA (Hibernate) 没有符合条件的 bean 类型:javax.persistence.EntityManagerFactory【英文标题】:Spring JPA (Hibernate) No qualifying bean of type: javax.persistence.EntityManagerFactory 【发布时间】:2014-01-15 11:51:27 【问题描述】:我正在使用 Spring-boot,因此在 Tomcat 7 中部署了一场战争。当我启动应用程序时,我得到以下信息:
Dec 30, 2013 7:41:06 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcherServlet'
2013-12-30 19:41:06 INFO DispatcherServlet:461 - FrameworkServlet 'dispatcherServlet': initialization started
2013-12-30 19:41:06 INFO SimpleUrlHandlerMapping:315 - Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2013-12-30 19:41:06 INFO RequestMappingHandlerMapping:181 - Mapped "[/user],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]" onto public com.cloudfordev.controlpanel.orm.User com.cloudfordev.controlpanel.GetController.getUser(int)
2013-12-30 19:41:07 INFO SimpleUrlHandlerMapping:315 - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2013-12-30 19:41:07 INFO SimpleUrlHandlerMapping:315 - Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2013-12-30 19:41:08 INFO DispatcherServlet:480 - FrameworkServlet 'dispatcherServlet': initialization completed in 1957 ms
Dec 30, 2013 7:41:08 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Dec 30, 2013 7:41:08 PM org.apache.tomcat.util.net.NioselectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Dec 30, 2013 7:41:08 PM org.apache.coyote.AbstractProtocol stop
INFO: Stopping ProtocolHandler ["http-nio-8080"]
Dec 30, 2013 7:41:08 PM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-nio-8080"]
Dec 30, 2013 7:41:08 PM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service Tomcat
Dec 30, 2013 7:41:08 PM org.apache.coyote.AbstractProtocol stop
INFO: Stopping ProtocolHandler ["http-nio-8080"]
Dec 30, 2013 7:41:08 PM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["http-nio-8080"]
2013-12-30 19:41:08 INFO AutoConfigurationReportLoggingInitializer$AutoConfigurationReportLogger:108 -
=========================
AUTO-CONFIGURATION REPORT
=========================
Positive matches:
-----------------
MessageSourceAutoConfiguration
- @ConditionalOnMissingBean (types: org.springframework.context.MessageSource; SearchStrategy: all) found no beans (OnBeanCondition)
PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer
- @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) found no beans (OnBeanCondition)
DataSourceAutoConfiguration
- @ConditionalOnClass classes found: org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)
- @ConditionalOnClass classes found: org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)
DataSourceTransactionManagerAutoConfiguration
- @ConditionalOnClass classes found: org.springframework.jdbc.core.JdbcTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)
- @ConditionalOnClass classes found: org.springframework.jdbc.core.JdbcTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)
JpaBaseConfiguration.JpaWebConfiguration
- found web application StandardServletEnvironment (OnWebApplicationCondition)
- SpEL expression on org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfiguration: #true (OnExpressionCondition)
DispatcherServletAutoConfiguration
- found web application StandardServletEnvironment (OnWebApplicationCondition)
- @ConditionalOnClass classes found: org.springframework.web.servlet.DispatcherServlet (OnClassCondition)
- found web application StandardServletEnvironment (OnWebApplicationCondition)
- @ConditionalOnClass classes found: org.springframework.web.servlet.DispatcherServlet (OnClassCondition)
- @ConditionalOnBean (types: org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; SearchStrategy: all) found the following [tomcatEmbeddedServletContainerFactory] (OnBeanCondition)
DispatcherServletAutoConfiguration#dispatcherServlet
- no DispatcherServlet found (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)
EmbeddedServletContainerAutoConfiguration
- found web application StandardServletEnvironment (OnWebApplicationCondition)
- found web application StandardServletEnvironment (OnWebApplicationCondition)
EmbeddedServletContainerAutoConfiguration.EmbeddedTomcat
- @ConditionalOnClass classes found: javax.servlet.Servlet,org.apache.catalina.startup.Tomcat (OnClassCondition)
- @ConditionalOnClass classes found: javax.servlet.Servlet,org.apache.catalina.startup.Tomcat (OnClassCondition)
- @ConditionalOnMissingBean (types: org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; SearchStrategy: current) found no beans (OnBeanCondition)
ServerPropertiesAutoConfiguration#serverProperties
- @ConditionalOnMissingBean (types: org.springframework.boot.context.embedded.properties.ServerProperties; SearchStrategy: all) found no beans (OnBeanCondition)
WebMvcAutoConfiguration
- found web application StandardServletEnvironment (OnWebApplicationCondition)
- @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet,org.springframework.web.servlet.config.annota
tion.WebMvcConfigurerAdapter (OnClassCondition)
- found web application StandardServletEnvironment (OnWebApplicationCondition)
- @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet,org.springframework.web.servlet.config.annota
tion.WebMvcConfigurerAdapter (OnClassCondition)
- @ConditionalOnMissingBean (types: org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; SearchStrategy: all) found no beans (OnBeanCondition)
WebMvcAutoConfiguration#hiddenHttpMethodFilter
- @ConditionalOnMissingBean (types: org.springframework.web.filter.HiddenHttpMethodFilter; SearchStrategy: all) found no beans (OnBeanCondition)
WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#defaultViewResolver
- @ConditionalOnMissingBean (types: org.springframework.web.servlet.view.InternalResourceViewResolver; SearchStrategy: all) found no beans (OnBeanCondition)
Negative matches:
-----------------
RabbitAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.amqp.rabbit.core.RabbitTemplate,com.rabbitmq.client.Channel (OnClassCondition)
AopAutoConfiguration
- required @ConditionalOnClass classes not found: org.aspectj.lang.annotation.Aspect,org.aspectj.lang.reflect.Advice (OnClassCondition)
BatchAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.batch.core.launch.JobLauncher (OnClassCondition)
JpaRepositoriesAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.data.jpa.repository.JpaRepository (OnClassCondition)
MongoRepositoriesAutoConfiguration
- required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.repository.MongoRepository (OnClassCondition)
DataSourceAutoConfiguration.DbcpConfiguration
- org.apache.commons.dbcp.BasicDataSource DataSource class not found (DataSourceAutoConfiguration.BasicDatabaseCondition)
DataSourceAutoConfiguration.EmbeddedConfiguration
- no embedded database detected (DataSourceAutoConfiguration.EmbeddedDatabaseCondition)
DataSourceAutoConfiguration.JdbcTemplateConfiguration
- no existing bean configured database (DataSourceAutoConfiguration.DatabaseCondition)
DataSourceAutoConfiguration.TomcatConfiguration
- org.apache.tomcat.jdbc.pool.DataSource DataSource class not found (DataSourceAutoConfiguration.TomcatDatabaseCondition)
DataSourceTransactionManagerAutoConfiguration#transactionManager
- @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found no beans (OnBeanCondition)
JmsTemplateAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.jms.core.JmsTemplate,javax.jms.ConnectionFactory (OnClassCondition)
DeviceResolverAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.mobile.device.DeviceResolverHandlerInterceptor,org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver (OnClassCondition)
HibernateJpaAutoConfiguration
- @ConditionalOnClass classes found: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,org.springframework.transaction.annotation.EnableTransactionManagement,javax.persistence.EntityManager,org.hibernate.ejb.HibernateEntityManager (OnClassCondition)
- @ConditionalOnClass classes found: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,org.springframework.transaction.annotation.EnableTransactionManagement,javax.persistence.EntityManager,org.hibernate.ejb.HibernateEntityManager (OnClassCondition)
- @ConditionalOnBean (types: javax.sql.DataSource; SearchStrategy: all) found no beans (OnBeanCondition)
ReactorAutoConfiguration
- required @ConditionalOnClass classes not found: reactor.spring.context.config.EnableReactor (OnClassCondition)
ThymeleafAutoConfiguration
- required @ConditionalOnClass classes not found: org.thymeleaf.spring3.SpringTemplateEngine (OnClassCondition)
EmbeddedServletContainerAutoConfiguration.EmbeddedJetty
- required @ConditionalOnClass classes not found: org.eclipse.jetty.server.Server,org.eclipse.jetty.util.Loader (OnClassCondition)
MultipartAutoConfiguration
- @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.multipart.support.StandardServletMultipartResolver (OnClassCondition)
- @ConditionalOnClass classes found: javax.servlet.Servlet,org.springframework.web.multipart.support.StandardServletMultipartResolver (OnClassCondition)
- @ConditionalOnBean (types: javax.servlet.MultipartConfigElement; SearchStrategy: all) found no beans (OnBeanCondition)
WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#beanNameViewResolver
- @ConditionalOnBean (types: org.springframework.web.servlet.View; SearchStrategy: all) found no beans (OnBeanCondition)
WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#viewResolver
- @ConditionalOnBean (types: org.springframework.web.servlet.View; SearchStrategy: all) found no beans (OnBeanCondition)
WebSocketAutoConfiguration
- required @ConditionalOnClass classes not found: org.springframework.web.socket.WebSocketHandler (OnClassCondition)
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:356)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1180)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:660)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:552)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:293)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:749)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:738)
at com.cloudfordev.controlpanel.Application.main(Application.java:14)
... 6 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:559)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:515)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:682)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:655)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:353)
... 22 more
这就是我的应用程序的启动方式:
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application
public static void main(String[] args)
SpringApplication.run(Application.class, args);
当我的 Spring 控制器处理连接时:
@Controller
public class GetController
private UserService userService;
@Autowired
public void setUserService(UserService userService)
this.userService = userService;
@RequestMapping(value = "/user", method = RequestMethod.GET)
public @ResponseBody User getUser(@RequestParam(value="id", required=true) int id)
User user = null;
user = userService.getUser(id);
return user;
它在 userService 上执行 getUser:
@Component
public class UserService
private UserDAO UserDao;
public UserDAO getUserDao()
return UserDao;
@Autowired
public void setUserDao(UserDAO UserDao)
this.UserDao = UserDao;
public User getUser(int id)
return getUserDao().load(id);
其中使用userDao查找实体:
@Repository("userDao")
@Transactional(propagation=Propagation.REQUIRED)
public class UserDAO
@PersistenceContext
private EntityManager entityManager;
public void insert(User user)
entityManager.persist(user);
public User load(int id)
return entityManager.find(User.class, id);
我在 /src/main/resources 中有以下 spring-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.mydomain.orm" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:/persistence.xml" />
<property name="persistenceUnitName" value="userPersistenceUnit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="HSQL" />
<property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/mydb" />
<property name="username" value="my_user" />
<property name="password" value="" />
</bean>
</beans>
最后但并非最不重要的是以下 /src/main/resources/persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="1.0">
<persistence-unit name="userPersistenceUnit" transaction-type="RESOURCE_LOCAL" >
<class>com.mydomain.orm.User</class>
</persistence-unit>
</persistence>
我需要做什么来解决这个错误?
【问题讨论】:
为什么要在控制器内部创建上下文,然后在方法中再次销毁? 老实说,我不知道 :( 我是上下文、bean、jpa 和休眠的新手。我猜上下文应该由 servlet 事务自动创建...我关闭它是因为 Eclipse对资源泄漏感到不安。 你不应该以这种方式创建上下文,只需通过@Autowired UserService
将你的UserService注入你的控制器。
@LeonardBrünings 我更新了 GetController。你的意思是这样吗?这似乎好多了。
我将改进后的代码添加到我的答案中。
【参考方案1】:
您想要一个EntityManager
注入,但您在该字段上没有任何注入注释,并且“工厂”在任何情况下都是错误的限定符。使用@PersistenceContext
注释您的字段,如果需要区分多个持久性单元,请使用unitName
。
对已编辑问题的回答:您的 XML 文件未包含在内,因为您从 Application
类开始,而 Spring 只是从那里遵循 @ComponentScan
。将此导入添加到您的 Application
类(或任何扫描的 @Configuration
类):
@ImportResource("classpath:spring-config.xml")
或者,您可以将 XML 配置迁移到 JavaConfig 格式,Spring 将对其进行组件扫描。
【讨论】:
您的 XML 文件未加载。我正在从 JavaConfig 中查找如何执行此操作。或者,您可以将所有内容迁移到 Java。 宾果游戏做到了!哦,谢谢你,Chrylis,当它奏效时,我高兴地大喊。我一直想知道它是否没有加载 spring-config.xml,但我一直认为这意味着类路径问题。耶它工作! 我会在计时器到期时奖励赏金。说吧,你觉得这里还有什么其他需要改进的地方吗? 除了使用 JavaConfig 和可能的 Spring Repository 而不是自定义 DAO(如果合适的话),不是真的。并且不要觉得有必要发布赏金,尤其是大的! 哦,你们两个肯定赚到了。在过去的几个小时里,我学到了很多东西......它的工作原理:)我希望我能奖励你们两个【参考方案2】:您的问题是您正在使用注释配置,该配置已经在类路径中搜索带注释的 bean,这会尝试实例化 UserDAO
,但您没有在此处提供 EntityManagerFactory。
您可以通过@ImportResource("classpath:spring-config.xml")
将JavaConfig 与XML 配置结合起来。
@Configuration
@ComponentScan
@EnableAutoConfiguration
@ImportResource("classpath:spring-config.xml")
public class Application
public static void main(String[] args)
SpringApplication.run(Application.class, args);
@Controller
public class GetController
@Autowired
UserService userService;
@RequestMapping(value = "/user", method = RequestMethod.GET)
public @ResponseBody User getUser(@RequestParam(value="id", required=true) int id)
return userService.getUser(id);
@Component
public class UserService
@Autowired
private UserDAO UserDao;
public User getUser(int id)
return getUserDao().load(id);
我是否建议将SpringData 用于 DAO,这样可以节省大量样板代码。
【讨论】:
哦,那好多了。我认为 Autowired 终于为我点击了。我想保存样板代码,但我很谨慎,在需要进步时再花几天时间学习。但我肯定会调查的,从现在开始。 @LynnOwens 如果你刚刚开始使用@Autowired
,我真的建议尽可能使用@Inject
。始终最好遵循(新)标准。
我现在已经让 SpringData 工作了......现在要调查@Inject【参考方案3】:
查看崩溃产生的自动配置报告,我可以看到没有定义DataSource
。如果你的类路径上有正确的东西,Spring Boot 会为你创建一个——例如,至少要让你的类路径中包含 h2 或 hsqldb 的东西正常工作。
顺便说一句,如果你以正确的方式使用 Spring Boot,XML 文件是多余的。
【讨论】:
谢谢,阅读本文后,我意识到我没有用于自动配置的 JDBC 驱动程序来构建依赖项。以上是关于Spring JPA (Hibernate) 没有符合条件的 bean 类型:javax.persistence.EntityManagerFactory的主要内容,如果未能解决你的问题,请参考以下文章
Spring、Spring Security、JPA、MySQL、Hibernate 配置
Spring JPA (Hibernate) 没有符合条件的 bean 类型:javax.persistence.EntityManagerFactory
使用 JPA 和 Spring 加载选定的 Hibernate 实体
spring.jpa.hibernate.hbm2ddl 和 spring.jpa.hibernate.ddl 之间的区别