简体   繁体   中英

How to create an instance of an implementation in Google Guice

I'm new to Google Guice and need a little help. I have created a module like this:

public interface Foo {
  Bar doSomething();
}

public class MyFoo implements Foo {
  Bar doSomething() {
    // create an instance of MyBar
  }
}

public interface Bar {
  void run();
}

public interface MyBar implements Bar {
  void run();
}

public class MyModule extends AbstractModule {

  @Override
  protected void configure() {
    bind(Foo.class).to(MyFoo.class);
  }      
}

My question is: What is the right way to create an instance of MyBar in class "MyFoo"? It feels wrong to just do this:

public class MyFoo implements Foo {
  Bar doSomething() {
    MyBar mybar = new MyBar();
    return mybar;
  }
}

Is there a way to inject a new instance of MyBar by MyModule when I need one, or do I have to inject a factory in the constructor of MyBar for creating MyBar instances? If I have to use a factory, can I control which implementation is generated via the module?

Maybe you are looking for providers? Providers are more or less factories which are part of the Guice API so you don't have to implement them.

public class MyFoo implements Foo {
  @Inject Provider<MyBar> myBarProvider;

  Bar doSomething() {
    return myBarProvider.get(); // returns a new instance of MyBar
  }
}

For details see https://github.com/google/guice/wiki/InjectingProviders

You can either go with Setter or Constructor Injection like below:

public class MyFoo implements Foo {

    //constructor based injector
    @Inject
    public MyFoo(MyBar myBar){
        this.myBar=myBar;
    }

     //setter method injector
    @Inject
    public void setBar(MyBar myBar){
        this.myBar=myBar;
    }

    Bar doSomething() {
    // create an instance of MyBar
  }
}

MyBar is an Interface in your case which can not be instantiated ,you have to provide concrete implementation for the same, then bind in your Module and Inject it either through Setter or Constructor Injection as stated above.

Setter Injection Example:

MyModule.java

import com.google.inject.AbstractModule;

public class MyModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(Foo.class).to(MyFoo.class);
        bind(Bar.class).to(MyBar.class);
    }
}

MyBar.java

public class MyBar implements Bar {

    public void run() {
        System.out.println("Hello Bar");
    }
}

MyFoo.java

import com.google.inject.Inject;

public class MyFoo implements Foo {
    private Bar bar;

    // setter method injector
    @Inject
    public void setBar(Bar myBar) {
        this.bar = myBar;
    }

    public Bar doSomething() {
        return bar;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM