Dagger 2 - How does marking a class constructor wi

2019-07-14 17:50发布

问题:

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 ! 
    }
    }

UPDATE: I wrote a blog on this feature incase anyone needs help: http://j2emanue.blogspot.ca/

回答1:

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