问题
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