Dagger 2란?

sangcomz
2 min readMar 9, 2016

--

Dagger 2

Dagger is a fully static, compile-time dependency injection framework for both Java and Android. -google

http://google.github.io/dagger/

의존성 주입(DI)?

일종의 디자인 패턴이다.

왜 의존성 주입이 필요한가?

  1. 모듈간의 결합도를 낮춘다.(테스트 코드를 짜기 좋다.)
  2. 코드를 깔끔하게 만들 수 있다.
  3. 재사용성이 높다.

Dagger 2 기본적인 사용 방법

1.Model class

public class TestModel {
String strTest;

TestModel(){
strTest = "test";
}

public String getStrTest() {
return strTest;
}

public void setStrTest(String strTest) {
this.strTest = strTest;
}
}

2.Module class

@Module
public class TestModule {
@Provides TestModel providesTestModel(){
return new TestModel();
}
}

3.Component Interface

@Component(modules = TestModule.class)
public interface TestComponent {
void inject(MainActivity target);
}

4.MainActivity

public class MainActivity extends AppCompatActivity {

TestComponent component;

@Inject TestModel testModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

component = DaggerTestComponent.builder().testModule(new TestModule()).build();
component.inject(this);

if (testModel != null)
Log.d("Dagger 2" , "testModel is not null");
}
}

Custom Scope와 SubComponent

Dagger 2에선@Singleton을 제공한다. Singleton은 같은 범위 내에서 하나의 인스턴스만을 반환한다.

SubComponent는 Component의 sub로 추가 될 수 있다. 이때 custom scope를 사용하면 SubComponent의 주기를 쉽게 관리할 수 있다.

scopes give us “local singletons” which live as long as scope itself.

http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/

@Singleton
@Component(modules = {AppModule.class, AndroidModule.class})
public interface AppComponent {
void inject(DemoApplication target);

ProfileComponent plus(ProfileModule ProfileModule);

SettingsComponent plus(SettingsModule settingsModule);
}

SubComponent에서 SubComponent

SubComponent에선 Inject와 Plus를 동시에 사용할 수 없다.

@Subcomponent(modules = { ProfileModule.class })
//@Component(modules = { ProfileModule.class })
public interface ProfileComponent {
// void inject(ProfileFragment target);
MoreComponent plus(MoreModule moreModule);
}

이런식으로 SubComponent를 등록한다. 그리고 필요하다면 SubComponent에 Scope를 지정할 수 있다. (Component와 Provides의 Scope는 동일해야 한다.)

@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface ProfileScope {
}
@ProfileScope
@Subcomponent(modules = { ProfileModule.class })
public interface ProfileComponent {
MoreComponent plus(MoreModule moreModule);
}
@Module
public class ProfileModule {
@Provides
@ProfileScope
public SomeBigObject providesSomeBigObject() {
return new SomeBigObject();
}
}

someBigObject는 항상 하나의 값을 반환한다.

결론

  1. Dagger 2 의 쓰임은 무궁무진할것같다. 한 번 실제로 써보면서 더 알고 싶다.
  2. 영어로된 자료는 엄청 많았다. 어느정도 읽을 수 있었지만 그래도 더 잘해야 겠다.
  3. Custom Scope때문에 하루가 지났다. 하지만 알고 보니 이런걸 갖고 하루나 고민했다니..라는 생각이 들었다.
  • 참고 사이트

http://www.vogella.com/tutorials/Dagger/article.html

--

--