Whats the meaning and purpose of @Inject
and / or @InjectView
annotations in Android / Java programming?
How can I use it?
Thanks in advance!
The @Inject annotation lets us define an injection point that is injected during bean instantiation.
Dependency injection provides your app with the following advantages: Reusability of classes and decoupling of dependencies: It's easier to swap out implementations of a dependency.
Android Annotations is an annotation-driven framework that allows you to simplify the code in your applications and reduces the boilerplate of common patterns, such as setting click listeners, enforcing ui/background thread executions, etc.
Dagger 2 is a compile-time android dependency injection framework that uses Java Specification Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are: @Module This annotation is used over the class which is used to construct objects and provide the dependencies.
For Android, these annotations are part of the Roboguice framework. They are used to provide dependency injection in an Android environment.
This allows you to directly inject an instance of the desired resource, whether it's a basic POJO, a view, or another resource. Here's a POJO example from the RoboGuice wiki:
class MyActivity extends RoboActivity {
@Inject Foo foo; // this will basically call new Foo();
}
This is a trivial one, but essentially the injection point is allowing your class to stay independent of creating/managing an instance of the injected Foo class and instead puts that responsibility on Foo itself by calling Foo's default constructor in this case. This allows for easier testing via something like mocks since MyActivity is free from the details of actual creating Foo itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With