java - 为什么这个 @ComponentScan 在我的 spring boot 应用程序中不起作用?

标签 java spring spring-boot

我正在学习 Spring Boot 。这是我的 spring boot 项目结构。我确实有意将我的 application.java 放在不同的包中以了解 @ComponentScan

项目来源 - https://github.com/kitkars/spring-boot

project structure

错误:

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注解的类应该在你的根包中(默认扫描这个包和子包中的所有类)或者你需要指定其他包(controllerentity 和其他)在 @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/

相关文章:

java - hibernate 二级缓存逐出特定实体

tomcat - 启用转发 header 后的 Spring Boot cookie 域问题

java - 在不对返回类型进行类型转换的情况下调用工厂

Spring 数据是否需要 hibernate

java - 我的投票系统已经很好但是

java - 如何在调用 LDAP 之前设置 Spring Security MD5 密码

jsp - Spring Boot和JSP无法渲染

java - 可以将java与jwt、rs256和auth0一起使用吗?

java - test !"".equals(someString) 的值是多少

java - this(<params>) 作为构造函数中的快捷方式?