我正在学习 Spring Boot 。这是我的 spring boot 项目结构。我确实有意将我的 application.java 放在不同的包中以了解 @ComponentScan
项目来源 - https://github.com/kitkars/spring-boot
错误:
The application failed to start due to below error. *************************** APPLICATION FAILED TO START *************************** Description: Field productRepository in com.test.service.ProductService required a bean of type 'com.test.repository.ProductRepository' that could not be found. The injection point has the following annotations: - @org.springframework.beans.factory.annotation.Autowired(required=true) Action: Consider defining a bean of type 'com.test.repository.ProductRepository' in your configuration. Process finished with exit code 1
这是我的 Application.java
@SpringBootApplication
@ComponentScan(basePackages = "com.test")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
现在,如果我将我的 Application.java
移动到 com.test
下,一切都会很好。
如果我的 Application.java 不在 com.test
下怎么办 - 它不能使用 ComponentScan
包并从那里开始吗?所有 Controller 、服务、存储库等都位于 com.test
下。
最佳答案
用@SpringBootApplication
注解的类应该在你的根包中(默认扫描这个包和子包中的所有类)或者你需要指定其他包(controller
、entity
和其他)在 @ComponentScan
中。
官方文档指出:
We generally recommend that you locate your main application class in a root package above other classes.
关于java - 为什么这个 @ComponentScan 在我的 spring boot 应用程序中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55750957/