這個問題放了好久都沒有管,今天解決了記錄一下(本來以為是什么很深奧的bug,結果發現是自己太菜了)
Caused by: java.lang.IllegalStateException: No fallbackFactory instance of type class com.*.*.*.api.factory.RemoteFallbackFactory found for feign client remoteService
目前項目使用的是SpringCloud,module配置是兩個無啟動類的module作為公共模塊,一個API做為所有module的遠程接口模塊,還有一個common作為配置以及基礎工具模塊
之前自己公司項目的FeignClient都是在啟動類同目錄下,所以在啟動類加一個@EnableFeignClients注解,添加個掃描包就行,而且沒有配置過fallbackFactory,所以從來沒有接觸過這種問題。
實際上這種問題的出現,確實就是spring沒有掃描到這個bean,雖然已經加了@Component注解,但是由於是跟啟動類不同module,所以這個類掃描不到。
那么問題來了,springboot怎么樣去掃描組件呢?
查看@SpringBootApplication的源碼可以看到
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
...
}
其中@ComponentScan這個注解是掃描@SpringBootApplication所在包下的所有@Component注解標記的bean,並注冊到Spring容器中。這里源碼就省略了,基本就是類加載器加載了class文件,然后掃描其中是否有注解。
那如果想要注冊的bean不在包掃描路徑下怎么辦?
(1)在主類上使用@Import注解(本次不做解釋)
(2)使用spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.*.*.*.api.factory.RemoteUserFallbackFactory,\
com.*.*.*.api.factory.RemoteLogFallbackFactory
spring.factories文件是幫助spring-boot項目包以外的bean(即在pom文件中添加依賴中的bean)注冊到spring-boot項目的spring容器。由於
@ComponentScan
注解只能掃描spring-boot項目包內的bean並注冊到spring容器中,因此需要@EnableAutoConfiguration
注解來注冊項目包外的bean。而spring.factories文件,則是用來記錄項目包外需要注冊的bean類名。
具體參考: