匕首注射可以用静态方法完成吗?

Can dagger injection done in static method?

我有这个网络模块。我想在 ErrorUtils 的静态方法中注入网络模块。

@Module
public class NetworkModule {
    private final String END_POINT = "https://www.myurl.com/";

    @Provides
    @Singleton
    public OkHttpClient getOkHttpClient() {
            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
       }

    @Provides
    @Singleton
    public GsonConverterFactory getGsonConverterFactory() {
        return GsonConverterFactory.create();
    }

    @Provides
    @Singleton
    public Retrofit getRetrofit(OkHttpClient okHttpClient, GsonConverterFactory gsonConverterFactory) {
        return new Retrofit.Builder()
                .baseUrl(END_POINT)
                .client(okHttpClient)
                .addConverterFactory(gsonConverterFactory)
                .build();
    }

    @Provides
    @Singleton
    public RetrofitService getRetrofitService(Retrofit retrofit) {
        return retrofit.create(RetrofitService.class);
    }

我想在静态方法中注入这个模块:

public class ErrorUtils {
    @Inject
    static Retrofit retrofit;

    public static RestError parseError(Response<?> response) {

        **//showing error while writing this line**

        MyApplication.getComponent().inject(ErrorUtils.class);
        Converter<ResponseBody, RestError> converter = retrofit.responseBodyConverter(RestError.class, new Annotation[0]);

        RestError error;

        try {
            error = converter.convert(response.errorBody());
        } catch (IOException e) {
            return new RestError();
        }

        return error;
    }
}

我们如何在静态方法中注入模块,有什么建议吗?

可见Migrating from Dagger 1

Dagger 2 does not support static injection.

静态方法和变量通常不是一个好主意。在你的情况下,你可以让你的 ErrorUtils 成为一个对象,例如具有 @Singleton 范围。然后你可以正确地注入服务并正确地注入你的 errorUtils 而无需使用静态调用。

如果这不是一个选项,您可以只为您的组件提供一个 getter

@Component interface MyComponent {
    Retrofit getRetrofit();
}

然后使用该方法设置静态变量。