6

I come from the guice world and am looking for a way to do something similar to the Modules.override provided by Guice. I have a pattern where I create a base Module/AbstractBinder for my production and then in test I override the bindings that need to be changed.

In an ideal world I would like to simply either extends the Parent AbstractBinder and then implement the bindings to override the parent binder. Or the other alternative is to simply install the parent Binder and then override the bindings that I want for testing purposes.

public class IOCRestModule extends AbstractBinder {

    @Override
    protected void configure() {
        // Max timeout for rest calls is 20 seconds, this will come from properties later on.
        bind(20000).to(Integer.class).named("MAX_REST_REQUEST_TIMEOUT");
        bind("tcp://localhost").to(String.class).named("jms.url");
    }
}

public class IOCMockRestModule extends AbstractBinder {

    public static final Logger logger = Logger.getLogger(IOCMockRestModule.class.getName());

    @Override
    protected void configure() {
        install(new IOCRestModule());
        bind(200).to(Integer.class).named("MAX_REST_REQUEST_TIMEOUT");
        bind("vm://localhost").to(String.class).named("jms.url");

}

Is this possible to do, and is it recommended? I noticed when I did this that the bindings for the IOCRestModule were not overridden by the IOCMockRestModule. I am assuming I could add the install at the end and this may work but not sure if this will cause any issues later on.

Chris Hinshaw
  • 6,967
  • 2
  • 39
  • 65

1 Answers1

0

In hk2 you can have multiple bindings for the same thing. By default the oldest will take precedence, but you can change this by using rank. So I think the following code would change the ordering around:

@Override
protected void configure() {
    install(new IOCRestModule());
    bind(200).to(Integer.class).named("MAX_REST_REQUEST_TIMEOUT").ranked(10);
    bind("vm://localhost").to(String.class).named("jms.url").ranked(10);
}

This essentially gives this binding a higher rank than the one from the IOCRestModule, and that will then be used in Injection points first. You should note that if anyone looks for a list of Integer with name MAX_REST_REQUEST_TIMEOUT they will get two of them

jwells131313
  • 2,364
  • 1
  • 16
  • 26
  • Also moving the install after your other binds will work because of the rule that the oldest binding is selected if they have equal rank – jwells131313 Feb 10 '15 at 12:46