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);
    }
}
复制代码

 

posted @   Fredric_2013  阅读(246)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2015-04-11 mongodb(回滚)
2015-04-11 mongodb( 实现join)
点击右上角即可分享
微信分享提示