[dagger] Dependency Injection with Dagger2

1. Dependency Injection

Dependency Injection(의존성 주입)을 하려면 먼저 dependency에 대해 알아야 함

의존성(dependency)

의존성의 위험성

어떻게 의존성을 해결?

모듈 내에서 다른 모듈에 대한 객체를 생성하지 못하도록 하려면, 다른 방법으로 객체를 제공해야 됨
How?

의존성 주입(Dependency Injection, DI)

Problem

Dependency injector(or DI framework)?

지금까지의 내용을 예제를 통해 쉽게 다시 복습

http://www.slideshare.net/baejjae93/dependency-injection-36867592

의존성 주입의 중요한 장점들

2. Dependency Injection with Dagger2

What is Dagger?

Dagger는 low-end devices를 위해 설계된 dependency injector.

JSR-330 이란?

‘Dependency Injection for Java’는 재사용 확대, 자바 코드의 테스트 가능성과 유지 가능성을 위해 표준 어노테이션들을 정의했습니다. Dagger 1 과 2 모두 이 표준을 사용해서 일관성을 유지하고, 의존성 주입의 표준 방법을 제공함

Dagger2 API

@Inject annotation

@Module annotation

모듈들은 의존성을 제공하는 메서드들을 가진 클래스입니다. 의존성을 제공하는 클래스를 정의하고 @Module 어노테이션을 답니다. 그러면 Dagger 는 클래스 인스턴스를 만들 때 의존성을 만족시키기 위한 정보를 찾을 수 있습니다.

@Provide annotation

모듈 안에서 해당 어노테이션이 달린 메서드를 정의합니다. 해당 어노테이션이 달린 메서드가 Dagger 가 어떻게 의존성에 맞게 객체를 만들고 제공하는지 알려줍니다.

@Component annotation

컴포넌트는 @Inject 와 @Module 사이 다리이며 의존성을 주입하는 역할을 합니다. 컴포넌트는 미리 정의한 모든 타입의 인스턴스를 줍니다. @Component 어노테이션은 인터페이스에다만 달아야합니다 그리고 컴포넌트를 구성하는 모든 @Module 이 달린 클래스 목록을 적어야합니다. 컴포넌트에서 사용하는 모듈들중 하나라도 없다면 컴파일 타임에 에러를 만듭니다. 모든 컴포넌트들은 컴포넌트에 포함된 모듈들을 통해 의존성의 범위를 알 수 있습니다.

@Scope annotation

스코프는 매우 유용하고 Dagger 2 에서 사용자 정의 어노테이션을 통해 범위를 나누는 명확한 방법입니다. 나중에 예제에서 보겠지만 이것은 매우 강력한 기능입니다. 앞에서 언급한바와 같이 하기 때문에, 모든 객체는 자기 자신의 인스턴스를 관리하는 방법에 대해 알필요가 없습니다. 예를들어 사용자가 지정한 @PerActivity 어노테이션이 달려있는 클래스는 액티비티가 살아있는 동안 존재합니다. 다시말하자면 객체 범위의 단위를 정의할 수 있습니다.

참고자료
http://frogermcs.github.io/dependency-injection-with-dagger-2-the-api/

Setup

Android Studio by default will not recognize a lot of generated Dagger 2 code as legitimate classes, but adding the android-apt plugin will add these files into the IDE class path and enable you to have more visibility. Add this line to your root build.gradle:

 dependencies {
     // other classpath definitions here
     classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
 }

Then make sure to apply the plugin in your app/build.gradle:

// add after applying plugin: 'com.android.application'  
apply plugin: 'com.neenbedankt.android-apt'

Add these three lines to your app/build.gradle file after this apply statement:

dependencies {
    // apt command comes from the android-apt plugin
    apt 'com.google.dagger:dagger-compiler:2.5'
    compile 'com.google.dagger:dagger:2.5'
    provided 'javax.annotation:jsr250-api:1.0'
}

참고 자료