我们通过下拉向导使用HK2作为依赖注入框架,从而实现了Jersey2.0。随着下拉向导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) {所以,这个曾经适用于我们。但是现在,通过可选的更改,如果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,但电话立即中断。
发布于 2020-01-30 10:52:35
下面是我的工作,如果我错过了你的设置,请让我知道:
@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;
}
}
}发布于 2020-11-05 23:28:58
事实上,在hk2的可选注入特性中似乎有一些bug,这些bug在这里是https://github.com/eclipse-ee4j/glassfish-hk2/pull/516修复的,应该是未来版本的一部分。
https://stackoverflow.com/questions/58218383
复制相似问题