HK2 Джерси. Как достать боб из контейнера? - PullRequest
0 голосов
/ 28 апреля 2018

У меня есть цепочка функций. Я хотел бы bind некоторые бобы внутри ConfigFeature, а затем получить их внутри MongoDBFeature. Какие методы я должен использовать для этого?

public final class IoCBinder extends AbstractBinder {

    @Override
    protected void configure() {
        ConfigFeature.configureIoC(this);
        MongoDBFeature.configureIoC(this);

    }
}

Положите немного бобов сюда:

public class ConfigFeature {
    public static void configureIoC(AbstractBinder binder) {
        // ....
        binder.bind(configProvider).to(ConfigurationProvider.class).in(Singleton.class).named("configProvider");
    }
}

И я бы хотел получить боб configProvider здесь:

public class MongoDBFeature {
    public static void configureIoC(AbstractBinder binder) {
        // ?? get configProvider here ??
    }
}

1 Ответ

0 голосов
/ 02 мая 2018

Вы можете привязать свой бин к ServiceLocator, как показано в примере ниже.

Услуги

public class TestService{

}

Binder

public static TestBinder extends AbstractBinder{
     @Override
     protected void configure() {
         bind(new TestService()).to(TestService.class);
     }
}

Функция 1

public class Feature1 implements Feature{

    @Inject
    private ServiceLocator locator;

    @Override
    public boolean configure(FeatureContext context) {
        org.glassfish.hk2.utilities.ServiceLocatorUtilities.bind(locator,new TestBinder());
        return true;
    }

}

Обратите внимание, что экземпляр ServiceLocator внедрен в Feature1 и binder привязан к этому экземпляру локатора.

Особенность 2

public class Feature2 implements Feature{

    @Inject
    private TestService testService;

    @Override
    public boolean configure(FeatureContext context) {
        return true;
    }

}

Класс Application / ResourceConfig

public class TestConfig extends ResourceConfig {
    register(Feature1.class);

    // Need to make sure Feature1 is registered before Feature2. 
    // Another option is to register Feature2 in configure() method of Feature1 class.
    register(Feature2.class);
}
...