【问题标题】:Why is bean not found during Spring Boot?为什么Spring Boot期间找不到bean?
【发布时间】:2019-07-30 12:53:05
【问题描述】:

这个问题已经解决了。请参阅下面的检查答案。

我将我的 DAO 重新配置为一种更方便的方式(通过使用 JpaRepository),而不是手动执行所有样板代码。但是现在每次我启动 Spring Application 时都会出现以下错误:

***************************

应用程序启动失败

说明:

DAO.UserDAOService 中的字段 userRepository 需要一个无法找到的“DAO.UserRepository”类型的 bean。

注入点有以下注解: - @org.springframework.beans.factory.annotation.Autowired(required=true)

行动:

考虑在您的配置中定义一个“DAO.UserRepository”类型的 bean。

进程以退出代码 1 结束

********************************************************************

【问题讨论】:

  • @Repository注释你的UserRepository
  • 因为它不是 bean。将@Repository 添加到它。
  • 我在标题中阅读了 Spring Boot,并认为您实际上在使用 Spring Boot
  • 我使用@SpringBootApplication 来运行我的应用程序
  • @SpringBootApplication 注解的类在什么包里?

标签: java spring hibernate spring-boot jpa


【解决方案1】:

除了前面的答案,IDE 经常会提示你错误的导入 Bean 类的注解,例如对于 @Service 注解的 bean,一定要导入:

import org.springframework.stereotype.Service;

而不是类似:

import org.jvnet.hk2.annotations.Service

【讨论】:

    【解决方案2】:

    解决方案:只需在 Spring 应用程序所在的同一包中创建子包。

    可以在此处找到解决方案示例:'Field required a bean of type that could not be found.' error spring restful API using mongodb

    【讨论】:

      【解决方案3】:

      1) 确保您的存储库类在 ApplicationConfiguration 类的子包中

      2) 使用@Repositiry注释存储库类

      【讨论】:

        【解决方案4】:

        添加 @Repository 注释,然后 bean 将在服务中创建并自动装配。

        import org.springframework.stereotype.Repository;
        
        @Repository
        public interface UserRepository extends JpaRepository<User , Integer>
        {
        }
        

        并且不需要在服务中创建bean

        @Bean
        public void setUserRepository(UserRepository userRepository)
        {
            this.userRepository = userRepository;
        }
        

        【讨论】:

        • 我这样做了,但我仍然收到此错误:*************************** 应用程序无法启动 * ****************************** 描述:DAO.UserDAOService 中的字段 userRepository 需要找不到类型为“DAO.UserRepository”的 bean。注入点具有以下注释: - @org.springframework.beans.factory.annotation.Autowired(required=true) 操作:考虑在您的配置中定义类型为“DAO.UserRepository”的 bean。进程以退出代码 1 结束
        • 删除了在控制器中创建服务@Bean 吗?
        • 是的,但它仍然给我同样的错误。它要么没有找到它,要么有多个 Bean 创建,但我已经在 userDAOService 和 UserController 类中使用相应的 set Methods 删除了注释。
        • 是否添加了 org.springframework.boot spring-boot-starter-data-jpa 作为依赖项?
        • 是的。只是想让你知道我解决了这个问题。 SPring 找不到存储库,因为它在另一个包中。我将存储库作为子包放置,但有些 spring 找不到服务。所以我通过为模型、服务、存储库和控制器制作子包以及 Spring 如何找到存储库来解决它。但感谢你坚持我 :) .
        【解决方案5】:

        您忘记在存储库类上添加注释。这就是 Spring 找不到该 bean 的原因。

        尝试在您的类定义之上添加@Repository

        【讨论】:

          猜你喜欢
          • 2022-11-10
          • 1970-01-01
          • 2018-12-13
          • 2018-10-01
          • 1970-01-01
          • 2017-12-13
          • 2019-07-16
          • 2017-11-05
          • 1970-01-01
          相关资源
          最近更新 更多