我有一个由多个模块组成的Maven项目。其中三个模块是
在启动时,出现以下异常:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.foo.bar.data.OrderRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
我知道默认情况下,Spring Boot Applications只在它们自己的子包中查找它们的子包,但是在这种情况下,bean在同级包中。我已经尝试过@ComponentScan({"org.foo.bar.data"})在Application类中添加一个,但无济于事。
@ComponentScan({"org.foo.bar.data"})
使用@EnableJpaRepositories(basePackages = {"org.foo.bar.data"})抛出
@EnableJpaRepositories(basePackages = {"org.foo.bar.data"})
Caused by: java.lang.IllegalArgumentException: Not an managed type: class org.foo.bar.core.model.Order
我究竟做错了什么?
目录树(已修剪)如下所示:
project ├── project-core │ └── src │ └── main │ └── java │ └── org │ └── foo │ └── bar │ └── core | └── model | └── Order.java ├── project-data │ └── src │ └── main │ └── java │ └── org │ └── foo │ └── bar │ └── data | └── OrderRepository.java │ └── project-spring └── src └── main └── java └── org └── foo └── bar └── spring └── Application.java
OrderRepository:
public interface OrderRepository extends JpaRepository<Order, Integer> { List<Order> findByDeliveryOverview(DeliveryOverview deliveryOverview); List<Order> findByDeliveryOverviewAndCustomer(DeliveryOverview deliveryOverview, Customer customer); }
应用程序
@SpringBootApplication @ComponentScan({"org.foo.bar.data"}) public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
主要问题是您的结构。
要扫描实体,您需要@EntityScan在应用程序类上启用,并启用所需的存储库@EnableJpaRepositories。
@EntityScan
@EnableJpaRepositories
@SpringBootApplication @EntityScan({"org.foo.bar.core.model"}) @EnableJpaRepositories(basePackages = {"org.foo.bar.data"}) public class Application { ... }
但是,我建议将Application类移至org.foo.bar,然后只需要使用,@SpringBootApplication因为它将从该目录开始扫描。
Application
org.foo.bar
@SpringBootApplication