2

I have a chain of Features. I would like to bind some beans inside ConfigFeature and then get them inside the MongoDBFeature. What methods should I use for that?

public final class IoCBinder extends AbstractBinder {

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

    }
}

Put some bean here:

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

And I would like to get configProvider bean here:

public class MongoDBFeature {
    public static void configureIoC(AbstractBinder binder) {
        // ?? get configProvider here ??
    }
}
Aleksey Kozel
  • 319
  • 1
  • 9
  • 16

1 Answers1

3

You can bind your bean to the ServiceLocator as shown in below example.

Service

public class TestService{

}

Binder

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

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

}

Note that a ServiceLocator instance is injected to Feature1 and the binder is bound to this locator instance.

Feature 2

public class Feature2 implements Feature{

    @Inject
    private TestService testService;

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

}

Application/ResourceConfig class

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);
}
Justin Jose
  • 2,121
  • 1
  • 16
  • 15