0

I want to be able to inject an object, and pass a parameter to its initializer method. Is this possible?

public class MyObject
{
  @Inject
  public MyObject(int anInteger)
  {
    //do something
  }
}


public class MyActivity extends RoboActivity
{
   @Inject (anInteger = 5) MyObject myObject;
   // I want to be able to pass an object to be used when calling the 
   // initializer method
}
4

2 回答 2

1

您应该能够做到这一点bindConstant()并相应地对其进行注释。例如,请参阅如何注入配置参数?

于 2011-03-30T01:53:11.437 回答
0
public class MyModule extends AbstractModule
{
  @Override
  protected void configure()
  {
    bind(Integer.class).
        annotatedWith(Names.named("my.object.an.integer")).
        toInstance(500);
  }

  @Provides
  @Named("an.integer.5")
  public MyObject myObject5()
  {
    return createMyObject(5);
  }

  @Provides
  @Named("an.integer.100")
  public MyObject providesMyObject100()
  {
    return createMyObject(100);
  }

  private MyObject createMyObject(int anInteger)
  {
    MyObject result = new MyObject(anInteger);
    // if there are any other fields/setters annotated with @Inject
    requestInjection(result);
    return result;
  }
}


public class MyObject
{
  public MyObject(int anInteger)
  {
    System.out.println("anInteger = " + anInteger);
  }
}

public class User
{
  @Inject
  @Named("an.integer.5")
  private field MyObject five;

  @Inject
  @Named("an.integer.100")
  private field MyObject hundred;
}
于 2011-03-30T06:28:08.733 回答