dagger2入门

    xiaoxiao2025-07-06  16

    1.什么是dagger2

    dagger2是一个依赖注入框架,在mvp的开发模式中,能使各模块在某种程度上能达到完全解耦的地布。但有点不好的是用android studio开发的时候,每次写个注入器或哪里使用了注入的时候都要重新build,dagger2具体定义我就不详细说了哈。

    2.怎么才能使用dagger2

    首先声明我用的android studio。首先我们在project级别的build.gradle文件中添加

    dependencies { classpath 'com.android.tools.build:gradle:2.1.2' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' }

    然后在module级别的build.gradle文件中添加

    apply plugin: 'com.neenbedankt.android-apt'dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.google.dagger:dagger:2.5' apt 'com.google.dagger:dagger-compiler:2.5' provided 'javax.annotation:javax.annotation-api:1.2' } 然后重新build就能愉快的在你的项目中使用dagger2了。

    3,使用时须知:

    1.@Inject:在须要用到的地方使用,如构造器,如成员变量等,eg:此时有A、B两个类,A如果要调用B,则可以在B的构造器上加上这个,如

    //这是B.java @Inject public B(){ } //这是A.java @ Inject B b;

    </pre><p></p><p>然后A文件中不需要对B进行实例化操作也就是new B()了,</p><p>2.@Module:这个里面用到了provide,从字面意思就能理解这是为@Inject提供实例化的一个工具,好吧,这只是我理解的,在上面那个粟子中,如果不在B的构造上使用@Inject,那么你可以在这里用</p><p><pre name="code" class="java">@PerActivity @Provide B provideB(){ return new B(); } A文件中不变。

    3.@Component:这是一个注入器,将依赖与被依赖的对象连接起来。就好像我们去图书馆借书,肯定是在你需要的那本书的类别的地方去找,不然去别的地方应该是找不到的(如果有同学放错地方了,那就无视),你可能说图书馆是不是就比作Component了,but我不是这么想的,我认为放你需要那些书的架子就是一个个Component,让你能够快速找到你所需,其他的就对号入座哈。

    4.@Scope:自定义注解,说是可以通过自定义注解限定注解作用域。

    5.@ Qualifier:这个有时候会很有用,比如说类名一样的两个文件就需要加一个这个来区分。

    4.实例讲解

    这是一个很简单的例子哈。现在我有MainActivity.java,Test.java,TestTwo.java,MainActivityComponent.java,TestModule.java,PerActivity.java这个类,见名知义哈。至于为啥有一个TestTwo.java,请见下文

    Test.java文件内容如下

    private TestTwo mTo; @Inject public Test(TestTwo to){ mTo = to; } public void doSomething(){ mTo.do(); } TestTwo.java:

    public TestTwo(){ } public void do(){ Log.i(TAG,"嘿嘿嘿"); } TestModule.java:

    @Module public class TestModule{ @PerActivity @Provide TestTwo provideTestTwo(){ new TestTwo(); } }PerActivity.java: @Scope @Documented @Retention(RetentionPolicy.RUNTIME) public @interface PerActivity { }

    MainActivityComponent.java:

    @PerActivity @Component(modules = TestModule.class) public interface MainActivityComponent{ void inject(MainActivity activity); } MainActivity.java:

    public class MainActivity extends AppCompatActivity{ private String TAG = "MainActivity"; @Inject Test test; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initEvent(); } public void initEvent() { DaggerMainActivityComponent.builder() .testModule(new TestModule()) .build() .inject(this); test.doSomething; } } 暂且就先只讲这么多吧。

    给你们个官方例子的链接吧:

    https://github.com/googlesamples/android-architecture?utm_source=tuicool&utm_medium=referral

    转载请注明原文地址: https://ju.6miu.com/read-1300434.html
    最新回复(0)