Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android @Inject and @InjectView annotations meaning

Whats the meaning and purpose of @Inject and / or @InjectView annotations in Android / Java programming?

How can I use it?

Thanks in advance!

like image 337
Geraldo Neto Avatar asked Aug 27 '15 00:08

Geraldo Neto


People also ask

What does @inject annotation mean?

The @Inject annotation lets us define an injection point that is injected during bean instantiation.

What is the use of @inject in Android?

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.

What is an annotation in Android?

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.

What is inject in dagger?

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.


1 Answers

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.

like image 93
whitlaaa Avatar answered Oct 27 '22 20:10

whitlaaa