2015-12-21 37 views
2

我的匕首已經設置了兩個組件。一個組件是另一個重要組件的子組件。一切正常。但後來我隨機想嘗試構造函數注入,所以我創建了一個隨機類,並用Inject註解標記了它的構造函數,當我想注入這個類時,我感到驚訝。我的組件對此一無所知。我沒有寫過關於這個類的組件接口。它只是一個隨機類,它有一個用@Inject註解的構造函數。這是如何工作的?這裏是隨機類:Dagger 2 - 如何使用@Inject標記類構造函數而不使用組件註冊工作

public class Knife { 

@Inject 
public Knife(){ 
    System.out.println("a spreading knife has been created"); 
}; 

}

,這裏是如何調用注入我的課,如果該事項:

public class MainActivity extends AppCompatActivity { 

    private final String TAG = getClass().getSimpleName(); 

    //@Inject 
    //AlmondButter someAlmondButter; 
    @Inject 
    CashewSandwich sandwich; 

    @Inject 
    CashewSandwich sandwich2; 

/*some how this is getting injected but its not in any component, how ?No ones 
providing it in a module either*/ 
    @Inject 
    Knife mKnife; 

    SandwichComponent sandwichComponent; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     /*create the dependent butter for the sandwich here*/ 
     ButterComponent butterComponent=DaggerButterComponent.builder(). 
       butterModule(new ButterModule()).build(); 
     /*create a scope sandwichcomponent here */ 

     sandwichComponent=DaggerSandwichComponent.builder().sandwichModule(new SandwichModule()). 
       butterComponent(butterComponent) 
       .build(); 
     //finally we have a sandwichComponent, lets inject our dependencies 
     sandwichComponent.inject(this); 

     Log.v(TAG," first:"+sandwich.toString()); 
     Log.v(TAG,"second:"+sandwich2.toString()); 
     Log.v(TAG,mKnife.toString()); //this actually works ! 
    } 
    } 

更新:我寫了一篇博客此功能櫃面有人需要幫助: http://j2emanue.blogspot.ca/

回答

2

在構造函數上放置@Inject使其對Dagger可檢測。您可以在JSR 330中閱讀更多關於它的信息。

+0

請問可以提供無範圍的話,我認爲 – j2emanue

+1

您可以添加一個範圍到類: ' @Singleton 類刀{ @Inject 公刀(){}} ' 我 – rdshapiro

+0

嘗試這樣有用。向課堂中添加一個範圍使其與活動範圍一樣長,謝謝。 – j2emanue

相關問題