https://google.github.io/dagger/
Dagger 공식 홈에 있는 CoffeeMaker 예제 단순화.
...
<dependencies>
<dependency>
<groupId>com.google.dagger</groupId>
<artifactId>dagger</artifactId>
<version>${dagger.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>com.google.dagger</groupId>
<artifactId>dagger-compiler</artifactId>
<version>${dagger.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
...
커피 머신이 작동하려면 커피 물을 끓일 Heater, 달여진 커피를 받을 Pump가 필요.
public interface Heater {
void on();
void off();
boolean isHot();
}
public class MyHeater implements Heater {
private boolean heating;
public void on() {
System.out.println("~ ~ ~ heating ~ ~ ~");
this.heating = true;
}
public void off() {
this.heating = false;
}
public boolean isHot() {
return heating;
}
}
public interface Pump {
void pump();
}
public class MyPump implements Pump {
private final Heater heater;
@Inject
public MyPump(Heater heater) {
this.heater = heater;
}
public void pump() {
if (heater.isHot()) {
System.out.println("=> => pumping => =>");
}
}
}
각 함수에 “provide” 접두사를 붙인다.
@Module
public class CoffeeMakerModule {
@Provides
Heater provideHeater() {
return new MyHeater();
}
@Provides
Pump providePump(MyPump pump) {
return pump;
}
}
public class CoffeeMaker {
@Inject
Heater heater;
@Inject
Pump pump;
@Inject
public CoffeeMaker(Heater heater, Pump pump){
this.heater = heater;
this.pump = pump;
}
public void brew(){
heater.on();
pump.pump();
System.out.println("brew!");
heater.off();
}
}
@Component(modules = CoffeeMakerModule.class)
public interface CoffeeComponent {
CoffeeMaker maker(); // getter 작성
}
먼저 Build를 하여 DI가 적용된 코드가 생성되도록 한다.
public class CoffeeApp {
public static void main(String... args) {
CoffeeComponent coffeeComponent = DaggerCoffeeComponent.create();
coffeeComponent.maker().brew();
}
}
~ ~ ~ heating ~ ~ ~
=> => pumping => =>
brew!