Dagger2demo学习笔记2

参考Dagger2的入坑指南[捂脸][详]!!
学习笔记1已经讲了基本的使用
现在有个需求,就要想要获取全局单例对象

通常做法:静态变量,或者单例模式封装,等…

Dagger2:使用@Singleton标识 保持单例,也可以使用自定义scope或者使用Reusable。先说说@Singleton

在学习笔记1的代码基础上改
module:只提供一个Gson 对象

	 @Singleton //就加了这个注解
    @Provides
    Gson provideGson() {
        return new Gson();
    }

Component

@Singleton//就加了这个注解
@Component(modules = UserModule.class)//可以有多个modules={xxxModule.class,XXclass,等等}
public interface MainComponent {
    //说明要在哪个activity注入
    void inject(MainActivity mainActivity);
}

activity注入两个Gson对象,因为上面两步标记了@singleton,所以生成的是单例

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    @Inject
    Gson gson1;
    @Inject
    Gson gson2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //在activity初始化
        DaggerMainComponent.builder().userModule(new UserModule()).build().inject(this);
        Log.e(TAG, Integer.toHexString(gson1.hashCode()));
        Log.e(TAG, Integer.toHexString(gson2.hashCode()));
    }
}

结果:
打印出地址,完全一致
要是把那两个@singleton注解去掉
结果就是非单例,可以看到下面两个Gson对象不一样
可以看到下面两个Gson对象不一样

注意:
module提供对象的方法用@Singleton注解声明,其Component也要用@Singleton注解声明。不然会编译不通过。
除了上面要module和Component要使用同一个之外。想要要保证对象的全局单例,Component只能构建一次。比如
A activity : 在A activity 注入

@inject
Gson gson;
DaggerMainComponent.builder().userModule(new UserModule()).build().inject(this);

B Activity :在B activity 注入

@inject
Gson gson;
DaggerMainComponent.builder().userModule(new UserModule()).build().inject(this);

这两个activity都作了以上的初始化,所以A和B的Gson是不可能是同一个对象的。所以要提供整个App的单例就必须保证初始化仅构建一次,也就是说在自定义Application构建。

public class MyApplication extends Application {

private DaggerMainComponent  daggerMainComponent;

 @Override
 public void onCreate() {
        super.onCreate();
   //构建初始化
    daggerMainComponent= DaggerMainComponent.builder().userModule(new UserModule()).build();

}

    public DaggerMainComponent   getDaggerMainComponent() {
        return daggerMainComponent;
    }

}

A activity 和 b activity 使用这两句完成注入初始化,就可以保持单例了

扫描二维码关注公众号,回复: 5493330 查看本文章
    MyApplication myApplication = (MyApplication) getApplication();
     myApplication.getDaggerMainComponent().inject(this);

猜你喜欢

转载自blog.csdn.net/weixin_43115440/article/details/88394623