dagger2 备注

dagger 2是android下的IOC框架,类似java服务端的spring,但功能上远没有其强大。个人理解不管是APP还是服务端依赖注入的本质都是一样的,用于解耦某个服务的定义和实现。我自己给出下面这个简单的例子:

1、在android studio中增加配置如下:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0',
        'com.neenbedankt.gradle.plugins:android-apt:1.4+'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
apply plugin: 'android-apt'

//此处要注意dagger的版本号 dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.2.0' compile 'com.android.support:design:23.2.0' compile 'com.google.dagger:dagger:2.0' apt 'com.google.dagger:dagger-compiler:2.0' provided 'org.glassfish:javax.annotation:10.0-b28' }

2、定义服务的实现如下:

public interface IStoreInfo {
    void storeInfo(String info);
}
public class StoreInfoInDb implements IStoreInfo{
    @Override
    public void storeInfo(String info) {
        System.out.println("In DB:" + info);
    }
}

public class StoreInfoInFile implements IStoreInfo{

    @Override
    public void storeInfo(String info) {
        System.out.println("In File:" + info);
    }
}

3、定义module和component

@Module
public class InfoServiceModule {

    @Provides
    @Singleton
    IStoreInfo setIStoreInfo(){
        return new StoreInfoInFile();
    }
}
@Singleton
@Component(modules = InfoServiceModule.class)
public interface InfoServiceComponent {
    void inject(InfoService service);
    IStoreInfo setIStoreInfo();
}

备注:这里其实相当于spring XML定义的部分,只是这里是采用硬编码的形式绑定接口的定义和实现

4、使用:

public class InfoService {

    @Inject
    public IStoreInfo info;

    public void initService(){
        InfoServiceComponent component = DaggerInfoServiceComponent.builder().infoServiceModule(new InfoServiceModule()).build();
        component.inject(this);
    }

    public void infoHandler(String input){
        info.storeInfo(input);
    }
}
原文地址:https://www.cnblogs.com/Fredric-2013/p/5379073.html