HK2命名为可选常量参数

问题描述 投票:0回答:1

我们通过dropwizard(因此使用jersey 2.0)将HK2用作依赖项注入框架。随着dropwizard 2.0的升级,似乎Optional parameters有了新功能。

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

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,但呼叫立即崩溃。

java jersey-2.0 hk2
1个回答
0
投票

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

@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() && sut.geoIpPath.get().equals("geoIpPath"));
        assertTrue(sut != null && !sut.geoIpPath.isPresent());
    }

    @Override
    public void before() {
        super.before();

        final String filesLocation = "filesLocation";
        // final Optional<String> geoIpPath = Optional.of("geoIpPath");
        final Optional<String> geoIpPath = Optional.empty();

        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");
            }
        });

        sut = testLocator.getService(GeoIpUtil.class);
    }

    @Service
    public static class GeoIpUtil {

        private final Optional<String> geoIpPath;

        @Inject
        public GeoIpUtil(@Named("geoIpPath") final Optional<String> geoIpPath) {
            this.geoIpPath = geoIpPath;
        }
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.