依赖注入框架解析

前端之家收集整理的这篇文章主要介绍了依赖注入框架解析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

依赖注入

使用

ButterKnife
在setContentView(..);之后加入ButterKnife.bind(this),
@BindView(R.id.testFre)SimpleDraweeView testFre;
@BindView(R.id.test)TextView test;

Dagger2:

场景:想在一个类中使用新建另外一个类,但是又觉得显示创建耦合性太高,所以使用Dagger。其实Dagger的使用是比较简单的,主要在需要新建一个类和一个接口:

1、新建Module类:

  1. @Module
  2. public class DemoModule {
  3. @Provides
  4. Person providePerson(){//声明需要依赖注入的类,方法名可以是任意的
  5. return new Person();
  6. }
  7. }

2、新建Component接口:

  1. @Component(modules=DemoModule.class)
  2. public interface DemoComponent {
  3.  
  4.  
  5. void inject(Dagger2Activity activity);//设置需要在那个类里进行依赖注入,也就是声明宿主
  6. Person getPerson();//这是依赖注入的第二种方法,一般用在全局设置中,如框架整合
  7.  
  8. }

3、两种形式的使用,请注意区别:

  1. 第一种实现
  2. public class Dagger2Activity extends AppCompatActivity {
  3.  
  4. @Inject
  5. Person person;//使用@Inject在宿主Dagger2Activity中依赖注入Person,
  6.  
  7. @Override
  8. protected void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.activity_dagger2);
  11. //特别注意DaggerCarComponent是Dagger2自动生成的,需要reBuild或者Make Project生成
  12. DemoComponent component = DaggerDemoComponent.builder().build();
  13. //进行注入
  14. component.inject(this);
  15. Log.i("111",person.toString());
  16. }
  17. }
  18.  
  19.  
  20. 第二种实现
  21. public class Dagger2Activity extends AppCompatActivity {
  22.  
  23.  
  24. Person person;//第二种实现
  25.  
  26. @Override
  27. protected void onCreate(Bundle savedInstanceState) {
  28. super.onCreate(savedInstanceState);
  29. setContentView(R.layout.activity_dagger2);
  30. //特别注意DaggerCarComponent是Dagger2自动生成的,需要reBuild或者Make Project生成
  31. DemoComponent component = DaggerDemoComponent.builder().build();
  32. //进行注入
  33. component.inject(this);
  34. person=component.getPerson();
  35. Log.i("111",person.toString());
  36. }
  37. }

需要注意的是Dagger2主要进行模块间的解耦,这里是最简单的使用demo。一般来说会配合MVP设计模式,以及一些其他的网络或者图片框架(Retrofit,RxAndroid,glide,Gson)使用,这些整合并不冲突。

MVP+Dagger2:这里假设已经已经搭好了简单的MVP架构。

1、新建一个Module类和Component接口

  1. @Module
  2. public class UserModule {
  3.  
  4. private final IUserView view ;
  5. public UserModule(IUserView view){
  6. this.view = view ;
  7. }
  8. @Provides
  9. IUserView provideILogView(){
  10. return view;//注意这里选择使用IUserView作为依赖注入对象
  11. }
  12. }
  13.  
  14. @Component(modules = UserModule.class)
  15. public interface UserComponent {
  16. public void inject(MvpActivity activity);
  17. }

2、修改Presenter中的代码

  1. public class UserPresenter {
  2. private IUserView mUserView;
  3. private IUserModel mUserModel;
  4.  
  5. //修改代码
  6. public UserPresenter(IUserView view) {
  7. mUserView = view;
  8. mUserModel = new UserModelImpl();
  9. }
  10.  
  11. //修改代码
  12. @Inject
  13. public UserPresenter(IUserView view) {
  14. mUserView = view;
  15. mUserModel = new UserModelImpl();
  16. Log.i("xixi","依赖注入了presenter");
  17. }
  18.  
  19.  
  20.  
  21. public void saveUser( int id,String name) {
  22. mUserModel.getID();
  23. }
  24.  
  25. public void loadUser( int id) {
  26. UserBean user = mUserModel.load(id);
  27. mUserView.setName(user.getName()); // 通过调用IUserView的方法来更新显示
  28. }
  29. }

3、修改宿主类:

  1. @Inject
  2. UserPresenter mUserPresenter;
  3.  
  4. @Override
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.activity_mvp);
  8. //mUserPresenter = new UserPresenter( this);
  9. DaggerUserComponent.builder().userModule(new UserModule(this)).build().inject(this);
  10.  
  11. }

完成完成

MVP+Dagger2+Retrofit+RxAndroid+glide+Gson:

在MVp+Dagger2的基础上,可以进一步的将一些框架封装进来。大体思路如下:

1、将这些框架封装成一个完整的只暴露接口的类;

2、将这些类进一步封装到module中:

  1. @Module
  2. public class RetrofitModule {
  3.  
  4. @Provides
  5. public OkHttpClient provideOkHttpClient() {
  6. OkHttpClient okHttpClient = new OkHttpClient();
  7. //okHttpClient.setConnectTimeout(60 * 1000,TimeUnit.MILLISECONDS);
  8. //okHttpClient.setReadTimeout(60 * 1000,TimeUnit.MILLISECONDS);
  9. return okHttpClient;
  10. }
  11.  
  12. @Provides
  13. public Retrofit provideRetrofit(Application application,OkHttpClient okHttpClient){
  14. Retrofit retrofit = new Retrofit.Builder()
  15. .baseUrl("")
  16. .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 添加Rx适配器
  17. .addConverterFactory(GsonConverterFactory.create()) // 添加Gson转换器
  18. .client(okHttpClient)
  19. .build();
  20. return retrofit;
  21. }
  22.  
  23. @Provides
  24. protected HttpService provideGitHubService(Retrofit retrofit) {
  25.  
  26. return retrofit.create(HttpService.class);
  27. }
  28. }

HttpService代码如下:

  1. public interface HttpService {
  2.  
  3. @POST("test/{id}")
  4. Observable<UserBean> getData(@Path("id") int id);
  5. }

3、将这些module都封装到一个全局的AppComponent类中。

  1. @Singleton
  2. @Component(modules = {RetrofitModule.class,GlideServiceModule.class})
  3. public interface AppComponent {
  4.  
  5. HttpService getService();
  6.  
  7. GlideService getImageLoader();
  8. }

4、使用

Bufferknife

视图类以及资源的注入。
利用反射和注解。

  1. @NonNull @UiThread
  2. public static Unbinder bind(@NonNull Activity target) {
  3. View sourceView = target.getWindow().getDecorView();
  4. return createBinding(target,sourceView);
  5. }

其中sourceView是顶级装饰view,进一步追踪createBinding(target,sourceView)

  1. private static Unbinder createBinding(@NonNull Object target,@NonNull View source) {
  2. Class<?> targetClass = target.getClass();
  3. if (debug) Log.d(TAG,"Looking up binding for " + targetClass.getName());
  4. //核心方法1,返回一个Constructor
  5. Constructor<? extends Unbinder> constructor = findBindingConstructorForClass(targetClass);
  6.  
  7. if (constructor == null) {
  8. return Unbinder.EMPTY;
  9. }
  10.  
  11. //noinspection TryWithIdenticalCatches Resolves to API 19+ only type.
  12. try {
  13. //核心方法2
  14. return constructor.newInstance(target,source);
  15. } catch (IllegalAccessException e) {
  16. throw new RuntimeException("Unable to invoke " + constructor,e);
  17. } catch (InstantiationException e) {
  18. throw new RuntimeException("Unable to invoke " + constructor,e);
  19. } catch (InvocationTargetException e) {
  20. Throwable cause = e.getCause();
  21. if (cause instanceof RuntimeException) {
  22. throw (RuntimeException) cause;
  23. }
  24. if (cause instanceof Error) {
  25. throw (Error) cause;
  26. }
  27. throw new RuntimeException("Unable to create binding instance.",cause);
  28. }
  29. }

Dagger2

@Inject

@Module

@Provides

@Component(modules = HttpHelperModule.class)

未完待续。

注意

ButterKnife和Dagger2是有冲突的,

猜你在找的设计模式相关文章