markdown Dagger 2:Singleton例如.md

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Dagger 2:Singleton例如.md相关的知识,希望对你有一定的参考价值。

# Modules

```Java
@Module
public class ReceiversModule {
    @Provides
    @NonNull
    @Singleton
    public NetworkChannel provideNetworkChannerl () {
        return new NetworkChannel();
    }
}
```
```Java
@Module
public class UtilsModule {
    @Provides
    @NonNull
    @Singleton
    public RxUtilsAbs provideRxUtils(Context context) {
        return new RxUtils(context);
    }
    @Provides
    @NonNull
    @Singleton
    public NetworkUtils provideNetworkUtils(Context context, NetworkChannel networkChannel) {
        return new NetworkUtils (context, networkChannel);
    }
}
```
```Java
@Module
public class AppModule {
    private Context appContext;
    
    public AppModule(@NonNull Context context) {
        appContext = context;
    }
    @Provides
    @Singleton
    Context provideContext() {
        return appContext;
    }
}
```

# Component

```Java
@Component(modules = {AppModule.class, UtilsModule.class, ReceiversModule.class})
@Singleton
public interface AppComponent {
    void inject(MainActivity mainActivity)
    //void inject(SecondActivity secondActivity)
}
```
# Injection

```Java
public class MainActivity extends AppCompatActivity {

    @Inject RxUtilsAbs rxUtilsAbs;
    @Inject NetworkUtils networkUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        App.getComponent().inject(this);
    }

}
```
```Java
public class App extends Application {
    private static AppComponent component;
    public static AppComponent getComponent() {
        return component;
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        component = buildcomponent();
    }
    
    protected AppComponent buildComponent() {
        return DaggerAppComponent.builder()
                .appModule(new AppModule(this))
                .build();
    }
}
```

以上是关于markdown Dagger 2:Singleton例如.md的主要内容,如果未能解决你的问题,请参考以下文章

Dagger 2 构造函数注入等

Dagger 2 不注入 sharedPreference

Dagger 2 - 为啥我收到循环引用错误?

ruby 来自http://stackoverflow.com/questions/10039039/why-self-method-of-module-cannot-become-a-singlet

Dagger 2:@Component.Builder 缺少所需模块或组件的设置器:[appi.example.com.dagger.AppModule]`

Dagger 2 无法访问 Retrofit