1:如何将引入的jar(sdk)包中定义的bean加入到当前项目的spring容器中?
在sdk中通过在META-INF文件夹中,增加spring.factories文件,如下:
org.springframework.boot.autoconfigure.EnableAutoConfiguration:\
com.czb.config.EndPointInitProcessorConfig,\
com.czb.config.CzbPlatformClientConfig,\
com.czb.config.FeignClientErrorDecoderConfig
sdk指定的配置类中定义的bean(包括通过@Bean注解和Enable*注解指定的bean):
@Configuration
@EnableFeignClients(clients = { SupplierFeignClient.class })
@EnableConfigurationProperties({ CzbPlatformClientProperties.class })
public class CzbPlatformClientConfig {
@Bean
public CzbClientEndPoint czbClientEndPoint(CzbClientService czbClientService) {
CzbClientEndPoint clientEndPoint = new CzbClientEndPoint(czbClientService);
return clientEndPoint;
}
}
当jar包被引入到项目中时,这些bean会被自动加入到项目的容器中。实际上,我们在使用springboot时导入的许多starter,就可以直接使用许多对象,如redis的template等,就是通过这种方式实现的。(可以认为将spring.factories文件中指定的类文件,像项目中定义的类一样加载,注解也会生效)
2:如何将sdk中定义的接口(Controlle)引入当前项目?
可以直接将写好的Controller通过Spring Factories机制引入项目。但在实践中我们使用Endpoint来在SDK中定义接口,这样接口路径为/actuator/id/*。这样的好处是一般SDK中的接口路径不会与项目中的接口路径重复。(使用EndPoint需要引入actuator的jar包,它其实是用来做应用的健康检查。如果我们使用过Swagger,就会发现会有一些我们没有定义过的接口,怎么来的)EndPoint的引入是通过Spring Factories机制。
3:@FeignClient干什么的?怎么用?(引入openFeign的jar包)
后台常常需要调用第三方接口,之前我们使用的是apache的httpClient。而现在通过OpenFeign,大大降低了调用第三方接口的难度。使用如下:
@FeignClient(name = "feignClient", url = "0.0.0.0:8888", path = "/actuator/*",
configuration = {FeignClientErrorDecoderConfig.class })
public interface SupplierFeignClient {
/**
* 请求发送验证码
*
* @param phone
* @return 电话不对则返回错误信息
*/
@PostMapping("/VendorValidateCode")
public StatusResultModel validateCode(@RequestParam String phone);
/**
* 绑定供应商
* @param phone
* @param Code
* @param NjbxTenant
* @return
*/
@PostMapping("/binDingNjbxSupplier")
ResultModel<CzbSupplier> binDingNjbxSupplier(@RequestParam String phone, @RequestParam String Code,@RequestParam String NjbxTenant);
注意@ComponentScan扫描范围不包括@FeignClient,需要配合@EnableFeignClients使用。