【问题标题】:cannot set up H2 JPA database witih Spring Boot - error : no bean available to autowire无法使用 Spring Boot 设置 H2 JPA 数据库 - 错误:没有可用于自动装配的 bean
【发布时间】:2020-10-06 21:43:33
【问题描述】:

我遵循了使用 Spring Boot 构建 REST API 的教程。 https://spring.io/guides/tutorials/rest/

一切都很好,直到我尝试设置 @Configuration 来设置 h2 数据库连接。

我有一个仓库


import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
interface EmployeeRepository extends JpaRepository<Employee, Long> {}

我有一个@Entity:


@Entity
public class Employee {
    private @Id @GeneratedValue Long id;
    private String name;
    private String role;

    public Employee() {}
}

当然我有我的@SpringBootApplication


@SpringBootApplication
public class RestdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestdemoApplication.class, args);
    }

}

我得到的错误是在 LoadDatabase @Configuration 类中:

当我完全按照教程进行操作时,为什么会出现错误?教程是否缺少一些关键步骤或注释,还是我在某个地方搞砸了?

【问题讨论】:

  • 你没有显示包语句,那么如果你将你的接口标记为public会发生什么?此外,您没有显示您的构建文件;你包括spring-boot-starter-data-jpa吗?最后,IDE 是容易出错的。您尝试运行应用程序了吗?

标签: java spring-boot spring-data-jpa autowired spring-repositories


【解决方案1】:

您的存储库类需要使用@Repository 进行注释,以便它可以在 Spring 应用程序上下文中注册为 bean:

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}

此外,您的屏幕截图中的错误是 IDE 错误,试图预测启动时的运行时异常。在某些情况下,它可能是误报。

【讨论】:

  • 你的答案不正确; @Repository 在 Spring 数据存储库接口上不是必需的。
猜你喜欢
  • 2017-03-01
  • 1970-01-01
  • 2016-05-15
  • 2017-02-20
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 2019-01-12
  • 2015-08-06
相关资源
最近更新 更多