问题描述
我们已经基于编写了一个内部服务发现(SD)客户端,这意味着它提供了ServiceRegistry
和DiscoveryClient
接口以及Spring提供的其他一些抽象的实现。
使用我们的库的应用程序仅将其添加到其pom文件中,并通过其自己的实现InHouseDiscoveryClient
自动连接DiscoveryClient
<dependency>
<groupId>blah.blah<groupId>
<artifactId>inhouse-service-discovery-client<artifactId>
<dependency>
但是,最好不要使用代码来InHouseDiscoveryClient
,而是使用如下所示的DiscoveryClient
接口
# Good
@Autowired
DiscoveryClient client;
# Bad (binds app to a particular SD implementation)
@Autowired
InHouseDiscoveryClient client;
因此,我们需要在项目中添加spring-cloud-commons
。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
</dependency>
这是问题的开始 。
Commons库实际上自动连接了DiscoveryClient
两个附加实现SimpleDiscoveryClient
和CompositeDiscoveryClient
。
这为我们的客户带来了奇特的用户体验。
用户不仅拥有InHouseDiscoveryClient
,还拥有这些额外的bean。
是否可以防止spring-cloud-commons
的DiscoveryClient
实现自动装配?
如果是这样,是否可以在我们的库中而不是最终用户的应用程序中完成?
1楼
我最终在我的库中扩展了AutoConfigurationImportFilter
,以便从常见云中删除自动装配的bean。
我也删除了它的健康指标,但是我们有一个非常特殊的理由这样做-很可能希望保留它。
my.package
public class StratusDiscoveryExclusionFilter implements AutoConfigurationImportFilter {
private static final Set<String> SHOULD_SKIP = new HashSet<>(
Arrays.asList(
// DiscoveryClient Beans
"org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClientAutoConfiguration",
"org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration",
// Health indicators
"org.springframework.cloud.client.CommonsClientAutoConfiguration")
);
/**
* For each class name, provide an assocated boolean array indicated whether or not to include
*/
@Override
public boolean[] match(String[] classNames, AutoConfigurationMetadata metadata) {
boolean[] matches = new boolean[classNames.length];
for (int i = 0; i < classNames.length; i++) {
matches[i] = !SHOULD_SKIP.contains(classNames[i]);
}
return matches;
}
}
我想在我的图书馆的spring.factories
文件中添加对此的引用
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=my.package.MyExclusionFilter