1. 问题描述

使用 @Autowired 后无法找到bean

image-20210202233206025

image-20210202233403391

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-02-02 23:33:00.234 ERROR 11084 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field keyWordClient in com.xiaor.tweetclient.service.impl.TweetServiceImpl required a bean of type 'com.xiaorfeign.keywordfeign.service.KeyWordClient' 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.xiaorfeign.keywordfeign.service.KeyWordClient' in your configuration.

2. 原因

Spring Boot 默认扫描 @SpringBootApplication 所在类的同级包以及包中的 bean,而我们导入的 bean 不属于这个包下,因此找不到该 bean。

3. 解决方法

方法一

配置 XXXApplication.java,修改包的扫描路径。

@SpringBootApplication
@ComponentScan({"com.xxx","com.xxxxxx"})
public class TweetClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(TweetClientApplication.class, args);
    }

}

image-20210202233723259

方法二

排除扫描某个包,以此来排除扫描 bean

@SpringBootApplication
@ComponentScan(excludeFilters = {
        @ComponentScan.Filter(type = FilterType.REGEX,pattern = "com.xxx.xxx.*")
})
public class TweetClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScAClientApplication.class, args);
    }
}
  • FilterType.REGEX:正则表达式类型。