2013-10-06 37 views
0

比如我有一個類,獲取在構造函數中dependecy,像我可以在ejb中使用特定的方法進行依賴注入嗎?

class ExampleService() { 

    private Dependency dep; 

    public ExampleService(Dependency dep) { 
     this.dep = dep; 
    } 

} 

和Dependecy類:

class Dependency { 

    public static Dependency getInstance() { 
     return new Dependency(); 
    } 

    private Dependency() { 
     /*constructor implementation here*/ 
    } 

} 

我要注入Dependency.getInstance(的結果)的方法裝入ExampleService構造通過@Inject EJB註釋。可能嗎?怎麼樣?謝謝。

+1

是不是有一個原因,你不能單獨使用你的'Dependency' bean而不是試圖使它成爲一個基於代碼的單例? – chrylis

+0

@chrylis沒有理由。我是新手,現在閱讀這個範圍。謝謝。 –

回答

0

在CDI製片方法can be static,所以用你的榜樣,下面會工作得很好:

class ExampleService() { 

    private Dependency dep; 

    @Inject 
    public ExampleService(Dependency dep) { 
     this.dep = dep; 
    } 

} 

class Dependency { 

    @Produces 
    public static Dependency getInstance() { 
     return new Dependency(); 
    } 

    private Dependency() { 
     /*constructor implementation here*/ 
    } 

} 

然而,就像在評論你的問題中提到,有可能是取決於你更好的方法想。

相關問題