java - Spring Boot 组件扫描

标签 java spring spring-boot

我正在编写一个新的 Spring Boot 项目,其中我的根包名称是“com.example”。在我的 gradle 配置中,我添加了第三方库的依赖项,该库的根包名称为 "org.base"。现在,这个库有带有 @Component 注释的类,我想在我的代码中利用 @Autowired

在我的 Config 类中,我也在扫描第三方库的基础包。

@Configuration
@ComponentScan({"org.base", "com.example"})
public class ServiceConfig{...}

当我运行应用程序时,spring 无法从该库中查找/创建 bean,并且出现 bean not found 错误。

要使组件扫描正常工作,根包必须相同吗?

错误详细信息:UserService 需要类型为“org.base.util.CommonUtils”的 bean,但无法找到。

UserService 是我的服务

最佳答案

@ComponentScan 仅当类使用 spring 注释(如 @Component@Service 等)进行注释时才有效。如何解决此问题就是使用声明式的方式,使用@Bean到用@Configuration注释的类就可以解决这个问题。

关于java - Spring Boot 组件扫描,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56510113/

相关文章:

java - 如何返回Id插入存储过程+mybatis

java - 如何使用驼峰聚合将一条消息聚合到多个组中?

java - 尝试在 Spring Boot/Spring Security Web 应用程序中打开 .css 文件时,为什么会收到 "405 - Method Not Allowed"错误?

java - 迁移到 Spring Boot 2.x 后在哪里可以找到 Sleuth 的 Span.TRACE_ID_NAME 替代品?

java - 在java中从json数组生成Excel工作表报告

java - Hibernate 无法将 UUID 插入 VARCHAR 列

java - 测试非空字段的更好方法

spring - 我们可以为 filterChainProxy 中的单个过滤器链提供多种模式吗

java - 发送方如何知道接收方在使用 Spring Boot 的 JMS 中不可用?

java - 从批处理文件中发现 Java 安装在哪里?