gpt4 book ai didi

java - Spring Boot - 未找到所需的 bean - 但接口(interface)是在同一个类中定义的

转载 作者:行者123 更新时间:2023-12-02 08:08:46 24 4
gpt4 key购买 nike

当尝试在运行时运行以下示例 spring boot 代码时,我收到错误

Parameter 0 of method runner in springbootdemo.SpringbootDemoApplication required a bean of type 'springbootdemo.SpringbootDemoApplication$ReservationRepository' that could not be found.

这是我的示例代码:

@SpringBootApplication                                                                                                  
public class SpringbootDemoApplication {

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

@Bean
CommandLineRunner runner(ReservationRepository rr) {
return strings -> {
Arrays.asList("Les, Josh, Phil, Sasha, Peter".split(","))
.forEach(n -> rr.save(new Reservation(n)));

rr.findAll().forEach(System.out::println);
rr.findByReservationName("Les").forEach(System.out::println);
};
}


interface ReservationRepository extends JpaRepository<Reservation, Long> {

// select * from reservation where reservation_name = :rn
Collection<Reservation> findByReservationName(String rn);
}

@Entity
class Reservation {

@Id
@GeneratedValue
private Long id;

private String reservationName;

public Reservation() { // for JPA - god sake why :-(
}

public Reservation(String reservationName) {
this.reservationName = reservationName;
}

@Override
public String toString() {
return "Reservations{" +
"id=" + id +
", reservationName='" + reservationName + '\'' +
'}';
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}
}
}

由于界面存在,我无法弄清楚是什么导致了该问题,不是吗?

我正在使用来自 start.spring.io 的新启动器来发布 1.4.7.RELEASE

最佳答案

默认情况下,Spring 不解析内部存储库,因此您需要显式启用此功能。
只需在您的配置类(或应用程序启动类,它也是您的案例的配置)上使用 @EnableJpaRepositories 以及标志 considerNestedRepositories = true 即可。

@SpringBootApplication      
@EnableJpaRepositories(considerNestedRepositories = true)
public class SpringbootDemoApplication

EnableJpaRepository文档。

关于java - Spring Boot - 未找到所需的 bean - 但接口(interface)是在同一个类中定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48550598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com