【问题标题】:Spring Boot Bean 'Required bean of type that could not be found'Spring Boot Bean'找不到类型的必需bean'
【发布时间】:2018-06-12 12:05:59
【问题描述】:

我一直在努力学习如何使用 Spring Data,并创建了一个非常简单的项目来测试它。文件夹结构和applicationcontext.xml在这里显示:applicationcontext.xml and folder structure 我得到的错误显示在这里:console error output . 我的类路径上有 applicationContext 并声明了该类的 bean,知道我的问题可能是什么吗?谢谢。

编辑: 我已经更新了我的帖子以显示主类和 dao 类,以及我的 pom.xml 内容(此时,我想知道是否需要包含另一个依赖项......) main class dao (repository)

【问题讨论】:

  • 你能添加你的spring boot主类吗?您不需要 appcontxt xml。只需在您的 UserRepository 上添加 Component 或 Repository 注释,删除您的 appctx 文件并尝试。
  • 嗨 Praneeth - 我添加了主类供您检查。如果您发现我的错误,请告诉我
  • 您是否通过测试用例运行此程序。我在日志中看到通过 TestContextManager 捕获的异常。如果是,则添加 SpringBoot 测试用例和测试配置。
  • 好眼光Praneeth!但是,当我将该项目作为 Spring Boot 项目(没有测试)运行时,我仍然收到以下错误: 描述:com.connor.controller.RegisterController 中的字段 userRepository 需要一个名为“entityManagerFactory”的 bean,但无法找到。行动:考虑在您的配置中定义一个名为“entityManagerFactory”的bean。
  • 看起来您还没有创建 Bean EntityManagerFactory bean。您是否使用 spring-boot-starter-data-jpa 依赖项。如果是,那么 Spring boot 会为您创建一个默认的 EntityManagerFactory,如果不是,那么您需要自己注册一个 EntityManagerFactory。将其添加到配置类中并尝试。看到这里创建一个baeldung.com/the-persistence-layer-with-spring-and-jpa

标签: spring spring-boot orm spring-data spring-data-jpa


【解决方案1】:

我错过了您的应用程序日志中的以下行:

... o.s.b.f.xml.XmlBeanDefinitionReader : 从类路径资源 [applicationContext.xml] 加载 XML bean 定义

所以我假设你的 applicationContext.xml 文件根本没有加载。

任意添加

@ImportResource("classpath:applicationContext.xml")

到您的应用程序类或添加

@Repository 

对您的 UserRepository 类的注释。

在我看来,您应该尽可能避免混合使用 Java 和 XML Spring 配置。

【讨论】:

  • 嗨哈迪,感谢您的意见;正如我提到的,我开始学习春天。但是,如果我自动装配另一个 bean 并通过 xml 定义它 - 它可以毫无错误地注入。因此,我怀疑正在加载 .xml 文件。但是,正如您所建议的,我将从这里开始完全使用 java 配置,并删除了任何 xml。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2018-05-11
  • 2019-02-09
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 2022-11-10
  • 2020-05-09
  • 2018-12-13
相关资源
最近更新 更多