HK2泽西岛。如何从容器中获取bean?

时间:2018-04-28 14:09:17

标签: jersey-2.0 hk2

我有一系列功能。我想bind ConfigFeature内的一些bean,然后将它们放在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 bean:

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

1 个答案:

答案 0 :(得分:3)

您可以将bean绑定到ServiceLocator,如下例所示。

服务

public class TestService{

}

粘合剂

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

}

请注意,{1}}实例将注入Feature1,ServiceLocator绑定到此定位器实例。

功能2

binder

Application / ResourceConfig类

public class Feature2 implements Feature{

    @Inject
    private TestService testService;

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

}