Skip to content

Instantly share code, notes, and snippets.

@chenanze
Forked from daverix/Testing.java
Created September 13, 2016 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chenanze/298d054d169868d2d70c6f05dd66799b to your computer and use it in GitHub Desktop.
Save chenanze/298d054d169868d2d70c6f05dd66799b to your computer and use it in GitHub Desktop.
Dagger2 sub components example
package com.example;
import javax.inject.Scope;
import javax.inject.Singleton;
import dagger.Component;
import dagger.Module;
import dagger.Provides;
import dagger.Subcomponent;
public class Testing {
public class A {
}
@Scope
public @interface BScope {
}
@Scope
public @interface CScope {
}
@Module
public class AModule {
@Provides
public A provideA() {
return new A();
}
}
@Singleton
@Component(modules = AModule.class)
public interface ACompononent {
BComponent newBComponent();
}
@BScope
@Subcomponent
public interface BComponent {
CComponent newCComponent();
}
@CScope
@Subcomponent
public interface CComponent {
A getA();
}
public void test() {
ACompononent aCompononent = DaggerTesting_ACompononent.builder().aModule(new AModule()).build();
BComponent bComponent = aCompononent.newBComponent();
CComponent cComponent = bComponent.newCComponent();
A a = cComponent.getA();
}
}
package net.daverix.TransparentCalendarWidget2;
import javax.inject.Scope;
import javax.inject.Singleton;
import dagger.Component;
import dagger.Module;
import dagger.Provides;
import dagger.Subcomponent;
public class Testing {
public static class A {
}
public static class B {
private A a;
public B(A a) {
this.a = a;
}
}
public static class C {
private B b;
public C(B b) {
this.b = b;
}
}
@Scope
public @interface BScope {
}
@Scope
public @interface CScope {
}
@Module
public static class AModule {
public AModule() {
}
@Provides
public A provideA() {
return new A();
}
}
@Module
public static class BModule {
@Provides
public B provideB(A a) {
return new B(a);
}
}
@Module
public static class CModule {
public CModule() {
}
@Provides
public C provideC(B b) {
return new C(b);
}
}
@Singleton
@Component(modules = AModule.class)
public interface ACompononent {
BComponent newBComponent();
}
@BScope
@Subcomponent(modules = BModule.class)
public interface BComponent {
CComponent newCComponent();
}
@CScope
@Subcomponent(modules = CModule.class)
public interface CComponent {
C getC();
}
public void test() {
ACompononent aCompononent = DaggerTesting_ACompononent.create();
BComponent bComponent = aCompononent.newBComponent();
CComponent cComponent = bComponent.newCComponent();
C c = cComponent.getC();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment