每一年都奔走在自己热爱里

没有人是一座孤岛,总有谁爱着你

基于SpringBoot多模块项目引入其他模块时@Autowired无法注入的问题

1. 问题描述

1.1 启动Spring Boot项目时报 NoSuchBeanDefinitionExpetion 没有找到bean的实例,即spring没有实例化对象,也就无法根据配置文件执行依赖注入依赖错误

2. 问题原因

假设模块A需要引入模块B的依赖,并且需要注入模块B中的TestService对象。

第一步,需要在A的pom文件中引入B模块的依赖:

<dependency>
    <groupId>com.example</groupId>
    <artifactId>module-b</artifactId>
    <version>1.0</version>
</dependency>

第二步:在A中的测试类中注入B的TestService对象:

@Autowired
private TestService testService;

第三步:并且调用 TestService 的方法:

testService.test();

测试代码提示会报错:

在pom文件中引入需要模块的依赖后,在启动类扫描时扫描不到该依赖。这是因为模块A的@SpringBootApplication注解默认扫描范围为A的启动类所在的包

(com.example.modulea)及其子包,所以此时模块A并没有扫描到模块B的包,那么自然无法在模块A中注入模块B的Service类。

3. 解决方法

1. 如果两个模块的包路径相同,只需要在启动类扩大包扫描范围

@SpringBootApplication(scanBasePackages = {"com.liyh.service"})

 2. 如果两个模块的包路径不相同,加入引入依赖的包

@SpringBootApplication(scanBasePackages = {"com.liyh.service", "com.test.service"})

posted @ 2021-01-10 20:59  helloliyh  阅读(5102)  评论(0编辑  收藏  举报