If you have a look to the docs for the annotation, a @Module
annotated class defines a class that contributes to the dagger object graph. In the Spring framework for example, the equivalent would be the @Configuration
anntotation. It defines a configuration point for your object graph, where you declare which objects you want to be available for injection and their scopes.
As a simple example, let's say we want a singleton object to be used by any Activity in the app. It has to be created in the module:
@dagger.Module(injects = {MyActivity.class})
public class Module {
@Provides
@Singleton
public MySinletonBean provideMySingleton() {
return new MySinletonBean();
}
}
This will create a MySingleton
object which can be injected in MyActivity
. This is a very basic example, but we can perform other actions in the graph there, like using dependencies in the constructors:
@dagger.Module(injects = {MyActivity.class})
public class Module {
private DependencyBean dependency = new DependencyBean();
@Provides
@Singleton
public MySinletonBean provideMySingleton() {
return new MySinletonBean(dependency);
}
@Provides
@Singleton
public MySinletonBean provideMyOtherSingleton() {
return new MyOtherSinletonBean(dependency);
}
}
Then, in MyActivity
we need to access the graph for the application in the onCreate
method:
@Inject
MySingletonBean singleton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
((MyApplication) getApplication()).getGraph().inject(this);
}
So, who does create the object graph here? The MyApplication
class does it when your application starts (don't forger to add it in your androidManifest.xml
):
public class MyApplication extends Application {
private ObjectGraph graph;
public ObjectGraph getGraph() {
return graph;
}
@Override
public void onCreate() {
super.onCreate();
graph = ObjectGraph.create(new Module(this));
graph.inject(this);
}
}
So the execution flow in a dagger app would be:
The android app starts and the MyApplication
class builds the graph, parsing the @Module
annotated classes and keeping an instance of it.
Then, the classes declared in the module can access its objects just injecting themselves in the object graph. Gradle then will evaluate their @Inject
annotations and perform the dependency injections.