简体   繁体   中英

Play 2.4 Scala, How to inject a class with a parameter?

Im trying to refactor my app to use play 2.4 dependency injection instead of cake pattern.

How do you inject a class with parameter, for example

class A(valX: Int) { } // How do you Inject val X ?

class B @Inject() (a : A)

Usually you wouldn't pass a parameter like an Integer in dependency injection - you'd use different ways to pass it on, like via a method parameter or a setter method. Via dependency injection you can inject only instances that are under control of your dependency injection system.

This is a simple example:

public class MyClass {

  private int myParameterY;
  private final MyOtherClass myInjectedInstance;

  @Inject
  ComponentResults(MyOtherClass injectedInstance) {
    this.myInjectedInstance = injectedInstance;
  }

  // Pass myParameterX
  public void myMethodThatNeedXAndY(int myParameterX) {
    // Do something with myParameterX and myParameterY
  }

  // Use this setter to initialize myParameterY 
  public void setParameterY(int Y) {
    this.myParameterY = Y;
  }
}

Or if it is a constant you could use 'bind' in your Guice configuration.

bind(Integer.class).annotatedWith(Names.named("myParameterZ")).toInstance(1);

And then use this annotations to inject it:

@Named("myParameterZ")

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