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

标签 android dependency-injection dagger-2

我已经用两个组件设置了 Dagger 。一个组件是另一个组件的子组件,这很重要。一切正常。但后来我随机想尝试构造函数注入(inject),所以我创建了一个随机类,并用 Inject 注释标记了它的构造函数,令我惊讶的是,当我想要注入(inject)这个类时,它可以工作吗?我的组件对此一无所知。我的组件接口(interface)中没有写关于这个类的内容。它只是一个随机类,有一个用 @Inject 注释的构造函数。这是如何运作的?这是随机类别:

public class Knife {

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

}

如果重要的话,这里是如何调用注入(inject)我的类:

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中阅读更多相关信息。 .

关于android - Dagger 2 - 如何在没有组件注册的情况下使用 @Inject 标记类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34406316/

相关文章:

Android 将布局组织到子文件夹中

安卓。 MoPub 开发工具包。代码 fragment 集成

dependency-injection - 如何在 Spring.Net 中使用 IApplicationContext 注册对象?

java - Dagger 2 : Injected object might still be null before onAttach is called in fragment

android - 如何使用 Dagger 2 将上下文注入(inject) Presenter

java - 在路径 DexPathList 上找不到类

java - 检查数据是否已启用且可用/工作。如果用户是预付费且没有信用怎么办?

c# - 为 MVC 中的每个请求创建和销毁的 Controller 实例 - WebAPI - 要注入(inject)的依赖范围是什么?

java - Spring DI 同时有两个构造函数

android - 错误 [Dagger/MissingBinding] androidx.lifecycle.ViewModelProvider.Factory cannot be provided without an @Provides-annotated method