Simple Dagger2 (Pure Java)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dagger.Component; | |
import dagger.Module; | |
import dagger.Provides; | |
import javax.inject.Inject; | |
public class Main { | |
public static void main(String[] args) { | |
AnimalCry animalCry = new AnimalCry(); | |
animalCry.cry(); | |
} | |
static class AnimalCry { | |
@Inject | |
Animal animal; | |
AnimalCry() { | |
AnimalComponent component = DaggerMain_AnimalComponent.builder().build(); | |
component.inject(this); | |
} | |
void cry() { | |
System.out.println(animal.cry()); | |
} | |
} | |
interface Animal { | |
String cry(); | |
} | |
static class Cat implements Animal { | |
@Override | |
public String cry() { | |
return "nya"; | |
} | |
} | |
// Module | |
@Module | |
static class AnimalModule { | |
@Provides | |
static Animal provideAnimal() { | |
return new Cat(); | |
} | |
} | |
// Component | |
@Component(modules = AnimalModule.class) | |
interface AnimalComponent { | |
void inject(AnimalCry animalCry); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment