該proides GSON,改造和OkHttpClient匕首2注射不工作
的單身@Module
public class MyModule {
@Provides
@Singleton
Gson provideGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
return gsonBuilder.create();
}
@Provides
@Singleton
OkHttpClient provideOkHttpClient() {
OkHttpClient client = new OkHttpClient();
return client;
}
@Provides
@Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(BuildConfig.SERVER_BASE_URL)
.client(okHttpClient)
.build();
return retrofit;
}
}
,允許注入單身成活性和片段
@Singleton
@Component(modules={MyModule.class})
public interface MyComponent {
void inject(Activity activity);
void inject(Fragment fragment);
void inject(Application application);
}
該構建的主應用程序類的部件的模塊組件
public class MyApp extends Application{
private MyComponent component;
@Inject
Retrofit retrofit;
@Override
public void onCreate() {
super.onCreate();
component= DaggerMyComponent.builder()
.myModule(new MyModule()).build();
getComponent().inject(this); // inject retrofit here
}
public MyComponent getComponent() {
return component;
}
}
這是我所在的片段試圖注入Retrofit。
public class MyFragment extends Fragment {
@Inject
Retrofit retrofit;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
((MyApp)getActivity().getApplication()).getComponent().inject(this);
....
}
}
在MyApp和MyFragment中,retrofit實例都是null。
看起來好像沒什麼問題。 – Raghunandan
我以爲是相同的,但它沒有注入改造:( – Coder