【问题标题】:HK2 Jersey. How to get bean from container?HK2 泽西岛。如何从容器中获取 bean?
【发布时间】:2018-04-28 14:09:17
【问题描述】:

我有一系列功能。我想在ConfigFeature 中添加bind 一些豆子,然后将它们放入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 ??
    }
}

【问题讨论】:

    标签: jersey-2.0 hk2


    【解决方案1】:

    您可以将 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;
        }
    
    }
    

    请注意,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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      相关资源
      最近更新 更多