Dagger 2 - 如何在没有组件注册的情况下使用 @Inject 标记 class 构造函数

Dagger 2 - How does marking a class constructor with @Inject without component registration work

我已经用两个组件设置了匕首。一个组件是另一个组件的子组件,这很重要。一切正常。但是后来我随机想尝试构造函数注入,所以我创建了一个随机 class 并用 Inject 注释标记了它的构造函数,令我惊讶的是当我想注入这个 class 它有效吗?我的组件对此一无所知。我没有在我的组件界面中写过关于这个 class 的内容。它只是一个随机的 class,它有一个用 @Inject 注释的构造函数。这是如何工作的?这里是随机的 class:

public class Knife {

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

}

这里是如何调用注入我的 class 如果这很重要:

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/

在构造函数上放置 @Inject 可以让 Dagger 检测到它。您可以在 JSR 330.

中阅读更多相关信息