2013-02-27 47 views
0

我有下面的類:掛毯IoC的構造和注射

public class MyClass { 
    @Inject 
    private MyAnotherClass myAnotherClass; 

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

我需要做在構造函數中有些東西需要的myAnotherClass一個實例。不幸的是在構造函數代碼追着myAnotherClass注入,這意味着我在null執行操作...

當然,我可以初始化它經典的方式(MyAnotherClass myAnotherClass = new MyAnotherClass())直接在構造函數,但我不認爲這是在這種情況下做正確的事情。

你會建議什麼解決方案來解決這個問題?

回答

7

最佳選項:

public class MyClass { 
    private final MyAnotherClass myAnotherClass; 

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

T5-IOC然後將使用構造函數注入所以自己沒有必要爲 '新' 了MyClass。有關更多信息,請參閱Defining Tapestry IOC Services

或者:

public class MyClass { 
    @Inject 
    private MyAnotherClass myAnotherClass; 

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