不同的微服務之間相互調用,不可避免會使用到feign client。為了統一處理參數和請求地址等變化,我們一般會將這些API服務的請求參數dto、響應dto及Feign接口封裝在一個公共的dto項目中(為了防止jar包沖突和依賴傳遞,這里的feign starter包的作用域是provided),調用方引入這個項目jar包,就可以直接使用這些相關api服務。有的項目本身可能不需要Feign接口,只需要請求參數dto、響應dto,因此他們在自己的項目中沒有引入feign starter這個jar包,但在公共的dto項目中已經配置過Feign接口,自己項目中啟動時,springboot找不到feign的起步依賴(一般會提示"feign.Feign$Builder類找不到")項目就會報錯,最終啟動失敗。因為我們沒用到此Feign接口,此時我們便不想引入feign starter的包,而其他人又可能會用到這個feign接口,總不能將dto項目中的這個feign接口刪除掉以此來解決自己項目啟動報錯的問題。
其實此時可以使用springboot的Condition相關注解動態按條件創建bean 。如果項目中沒有feign starter這個jar包,spring不會創建feign接口的bean,若引入了這個jar包,就讓spring創建這個bean.
<!--dto項目中的maven依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
定義的feing接口
// dto項目中feign接口,此接口位於com.hello.feign.user包下
@FeignClient(value = "microservice-wxopen")
public interface WxUserFeign {
@GetMapping("/wx/by_open_id")
SingleResponse<WxUserInfoDTO> getUserByOpenId(@RequestParam(value = "openId") String openId);
}
配置feign
//dto項目中feign配置
@Configuration
@EnableFeignClients(basePackages = {"com.hello.feign"})
//這個feign.Feign是fein starter中的配置類,若不引入fein starter包不能在classpath
//找到這個類,此配置就不會生效,也就不會為WxUserFeign接口創建相應的bean
@ConditionalOnClass(feign.Feign.class)
public class WxOpenFeignConfig implements InitializingBean {
private final Logger log = LoggerFactory.getLogger(getClass());
@Override
public void afterPropertiesSet() throws Exception {
log.info("================ WxOpenFeignConfig配置生效===================");
}
}
