匕首2 - 如何标记类构造函数与@Inject没有组件注册工作 [英] Dagger 2 - How does marking a class constructor with @Inject without component registration work

查看:227
本文介绍了匕首2 - 如何标记类构造函数与@Inject没有组件注册工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有匕首已经设置了两个组成部分。一个组件是另一个大问题的一个子组件。一切正常。但后来我随意想尝试构造器注入,所以我创建了一个随机的类,标志着它与注入注释和让我吃惊的构造函数时我wnated注入​​这个类它的工作原理?我的份(S)对此一无所知。我没有写在我的组件接口关于这个类。它只是有@Inject注解构造一个随机类​​。这是如何工作?这里是Random类:

i have dagger already set up with two components. One component is a subcomponent of another, big deal. Everything works. But then i randomly wanted to try constructor injection so i created a random class and marked its constructor with the Inject annotation and to my surprise when i wnated to inject this class it works ? my Component(s) know nothing about this. I have no written in my components interface about this class. its just a random class that has a constructor annotated with @Inject. How is this working ? Here is the random class:

public class Knife {

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

}

和这里是如何调用注入我的班如果该事项:

and here is how call inject my class if that matters:

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 上的构造使得它检测到匕首。您可以在 JSR 330 阅读更多关于它。

Placing @Inject on a constructor makes it detectable to Dagger. You can read more about it in JSR 330.

这篇关于匕首2 - 如何标记类构造函数与@Inject没有组件注册工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆