Tapestry IoC constructor and injection

会有一股神秘感。 提交于 2019-12-25 14:46:45

问题


I have the following class:

public class MyClass {
    @Inject
    private MyAnotherClass myAnotherClass;

    public MyClass() {
        //Perform operations on myAnotherClass.
    }
}

I need to do some things in constructor which require an instance of myAnotherClass. Unfortunately myAnotherClass is injected after code in constructor is ran, which means I am performing operations on null...

I could of course instantiate it the classic way (MyAnotherClass myAnotherClass = new MyAnotherClass()) directly in constructor, but I don't think it is the right thing to do in this situation.

What solutions would you suggest to solve this problem?


回答1:


Best option:

public class MyClass {
  private final MyAnotherClass myAnotherClass;

  public MyClass(MyAnotherClass other) {
    this.myAnotherClass = other;
    // And so forth
  }
}

T5-IoC will then use constructor injection so there's no need to 'new' up MyClass yourself. See Defining Tapestry IOC Services for more info.

Alternatively:

public class MyClass {
  @Inject
  private MyAnotherClass myAnotherClass;

  @PostInjection
  public void setupUsingOther() {
    // Called last, after fields are injected
  }
}


来源:https://stackoverflow.com/questions/15121308/tapestry-ioc-constructor-and-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!