Developers, Developers, Developers! Maksim Sorokin IT Blog

19Feb/10Off

Java EE 6 Injection With Dynamic Parameter

Say, you want to inject an object using @javax.inject.Inject. And you would like to pass additional dynamic parameter upon initialization. You can do the following trick.

For instance you want to inject and object which depends on some input. In current case let it be Pencil object, which needs to be initialized with color.

public class Pencil {
  private Color color;

  void init(Color color) {
    this.color = color;
  }

  public void draw() {
    //
  }
}

In this case when you inject the Pencil, you have to call init(Color) explicitly, which is kind off error-prone. What you can do is create a PencilProducer which would create Pencil objects with desired color.

public class PencilProducer {
  @Inject private Instance pencilInstance;

  public Pencil produce(Colour color) {
    Pencil pencil = pencilInstance.get();
    pencil.init(color);
    return pencil;
  }
}

In this case PencilProducer will create new Pencil object every time it is called. And in the application you simply inject PencilProducer and call produce method when needed.

This may seem to be too straight and dirty, but hey -- no new keyword!

Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.