HK2 命名为可选常量参数



我们通过dropwizard使用HK2作为我们的依赖注入框架,因此是jersey 2.0。随着 dropwizard 2.0 升级,似乎有一个新功能 可选参数.

这破坏了我们注入各种配置字符串的使用,有些是可选的,有些不是。

bind(configuration.getFilesLocation()).to(String.class).named("filesLocation");
bind(configuration.getGeoIpPath()).to(new TypeLiteral<Optional<String>>() {
}).named("geoIpPath");
...
public GeoIpUtil(@Named("geoIpPath") Optional<String> geoIpPath) {

所以,这曾经为我们工作。但是现在,随着 Optional 的更改,如果configuration.getGeoIpPath()Optional.empty(),则GeoIpUtil类将获得configuration.getFilesLocation()值。因此,看起来当找不到命名注入时,HK2 会注入任何String绑定。所以即使我以正确的方式更改代码

if (configuration.getGeoIpPath().isPresent()) {
bind(configuration.getGeoIpPath().get()).to(String.class).named("geoIpPath");
}

HK2 仍将注入filesLocation.

有什么方法可以在不引入新类或传递整个configuration对象的情况下解决此问题?也许有一种让 HK2 严格检查命名绑定的方法?

我尝试将null注入String.class,但通话立即崩溃。

以下内容对我有用,如果我错过了您的一些设置,请告诉我:

@Classes({ MyTest.GeoIpUtil.class })
public class MyTest extends HK2Runner {
// @Inject (Inject manually)
private GeoIpUtil sut;
@Test
public void test() {
assertTrue(sut != null && !sut.geoIpPath.isPresent());
assertTrue(sut != null && sut.geoIpPath2.isPresent() && sut.geoIpPath2.get().equals("geoIpPath"));
}
@Override
public void before() {
super.before();
final String filesLocation = "filesLocation";
final Optional<String> geoIpPath = Optional.empty();
final Optional<String> geoIpPath2 = Optional.of("geoIpPath");
ServiceLocatorUtilities.bind(testLocator, new AbstractBinder() {
@Override
protected void configure() {
bind(filesLocation).to(String.class).named("filesLocation");
bind(geoIpPath).to(new TypeLiteral<Optional<String>>() {}).named("geoIpPath");
bind(geoIpPath2).to(new TypeLiteral<Optional<String>>() {}).named("geoIpPath2");
}
});
sut = testLocator.getService(GeoIpUtil.class);
}
@Service
public static class GeoIpUtil {
private final Optional<String> geoIpPath;
private final Optional<String> geoIpPath2;
@Inject
public GeoIpUtil(@Named("geoIpPath") final Optional<String> geoIpPath, @Named("geoIpPath2") final Optional<String> geoIpPath2) {
this.geoIpPath = geoIpPath;
this.geoIpPath2 = geoIpPath2;
}
}
}

事实上,hk2 的可选注入功能中似乎有一些错误,这些错误 https://github.com/eclipse-ee4j/glassfish-hk2/pull/516 在这里修复,应该成为未来版本的一部分

最新更新