我们正在 Spring Boot 1.5 中探索 Micrometer 指标收集库。
Micrometer 在 Tag
接口(interface)中提供了一个静态方法来为指标创建标签。
public interface Tag {
String getKey();
String getValue();
static Tag of(String key, String value) {
return new ImmutableTag(key, value);
}
}
ImmutableTag的实现如下:
public class ImmutableTag implements Tag {
private String key;
private String value;
public ImmutableTag(String key, String value) {
requireNonNull(key);
requireNonNull(value);
this.key = key;
this.value = value;
}
...other methods...
}
现在,我们以编程方式收集一些标签,最终可能会得到一个 null 标签(由于 requireNonNull()
,这将引发异常)。但遇到空值时,我们可以用默认字符串(例如“未知”)替换标签值。
处理这个问题的最佳方法是什么?
我想到了以下几点:
- Try/Catch:将所有此类语句放在
try/catch
block 中。我知道这可能很昂贵且难以维护。 - 在我们这边处理 null:
检查是否传递了任何 null 标记
,并将其替换为默认字符串。然而,我们会有很多这样的语句,并且希望有某种配置来默认发生这种情况。 - Wrapper 接口(interface):创建
TagWrapper 接口(interface)
,将 null 替换为默认值,然后调用Tag.of()
方法。现在对我来说似乎是最好的选择,但是,当不再需要它时(也许稍后会在库中引入这样的方法),摆脱包装器将包括很多更改。
Spring 中是否有一些配置允许我在不创建包装器的情况下预先处理第三方库方法?
最佳答案
也许使用 Spring AOP。像这样的东西:
@around(value="execution(* package.name.class.Tag.of)")
public void wrapTags(ProceedingJoinPoint call){
try {
Object[] args = call.getArgs();
// wrap args in Optional.ofNullable
call.proceed();
} catch (Exception e){
// handle exception
}
}
关于java - Spring Boot中预处理第三方库方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51503574/