Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an object using constructor injection?

Tags:

How would I create an instance of Dog with a component which provides Cat.

public final class Dog {     private final Cat mCat;     public final static String TAG = "Dog";      @Inject public Dog(Cat cat) {         mCat = cat;         Log.e(TAG, "Dog class created");     } } 

After experimenting with Dagger 2 for a while I have no idea how to use constructor injection – a hint would be nice, thanks.

Edit:
Whats wrong with the question? After using Dagger 2, following several tutorials and reading the official documentation I have no clue how to use the constructor injection feature, that's why I ask here. Instead of injecting the Cat dependency into Dog with @Inject I could write a DogModule providing a Dog object, but then Dog would be just a regular Java class. Field injection works great (there are a lot of examples showing how to use it) but what do I need to do to use constructor injection?

like image 726
Paradiesstaub Avatar asked Apr 25 '15 16:04

Paradiesstaub


People also ask

How does constructor injection work?

When a class requires an instance of a Dependency, you can supply that Dependency through the class's constructor, enabling it to store the reference for future use. Constructor Injection is the act of statically defining the list of required Dependencies by specifying them as parameters to the class's constructor.

How constructor injection works in Spring?

Constructor Based Dependency Injection. It is a type of Spring Dependency Injection, where object's constructor is used to inject dependencies. This type of injection is safer as the objects won't get created if the dependencies aren't available or dependencies cannot be resolved.

When would you use constructor based injection?

Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on the other class.


1 Answers

To create an object using the Dagger 2 constructor injection feature you need to add a method to a component which provides a Cat class.

@Component(     dependencies = ApplicationComponent.class,     modules = CatModule.class) public interface ActivityComponent {     void inject(final CatActivity a);     // objects exposed to sub-components     Cat cat();     Dog dog(); } 

An instance of Dog can then be retrived by calling [Component].dog().

final ActivityComponent comp = DaggerActivityComponent.builder()             .applicationComponent(app.getApplicationComponent())             .build();  final Dog d = comp.dog(); 
like image 114
Paradiesstaub Avatar answered Sep 21 '22 15:09

Paradiesstaub