当尝试在运行时运行以下示例spring引导代码时,出现错误


方法运行器中的参数0
springbootdemo.SpringbootDemoApplication需要一个类型为bean的bean
'springbootdemo.SpringbootDemoApplication $ ReservationRepository',
找不到。


这是我的示例代码:

@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的配置类(或Application starter类,这也是您的情况下的配置)上使用considerNestedRepositories = true

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


EnableJpaRepository文档。

10-06 05:32
查看更多