指南匕首2.x (修订版6):
步骤如下:
1.) add Dagger
给你的build.gradle
files:
.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' //added apt for source code generation
}
}
allprojects {
repositories {
jcenter()
}
}
.
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt' //needed for source code generation
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "your.app.id"
minSdkVersion 14
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
apt 'com.google.dagger:dagger-compiler:2.7' //needed for source code generation
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.google.dagger:dagger:2.7' //dagger itself
provided 'org.glassfish:javax.annotation:10.0-b28' //needed to resolve compilation errors, thanks to tutplus.org for finding the dependency
}
2.)创建您的AppContextModule
提供依赖项的类。
@Module //a module could also include other modules
public class AppContextModule {
private final CustomApplication application;
public AppContextModule(CustomApplication application) {
this.application = application;
}
@Provides
public CustomApplication application() {
return this.application;
}
@Provides
public Context applicationContext() {
return this.application;
}
@Provides
public LocationManager locationService(Context context) {
return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
}
3.)创建AppContextComponent
提供接口来获取可注入类的类。
public interface AppContextComponent {
CustomApplication application(); //provision method
Context applicationContext(); //provision method
LocationManager locationManager(); //provision method
}
3.1.)这是创建带有实现的模块的方法:
@Module //this is to show that you can include modules to one another
public class AnotherModule {
@Provides
@Singleton
public AnotherClass anotherClass() {
return new AnotherClassImpl();
}
}
@Module(includes=AnotherModule.class) //this is to show that you can include modules to one another
public class OtherModule {
@Provides
@Singleton
public OtherClass otherClass(AnotherClass anotherClass) {
return new OtherClassImpl(anotherClass);
}
}
public interface AnotherComponent {
AnotherClass anotherClass();
}
public interface OtherComponent extends AnotherComponent {
OtherClass otherClass();
}
@Component(modules={OtherModule.class})
@Singleton
public interface ApplicationComponent extends OtherComponent {
void inject(MainActivity mainActivity);
}
Beware:: 您需要提供@Scope
注释(如@Singleton
or @ActivityScope
)在模块的@Provides
带注释的方法来在生成的组件中获取作用域提供程序,否则它将被取消作用域,并且每次注入时都会获得一个新实例。
3.2.)创建一个应用程序范围的组件,指定您可以注入的内容(这与injects={MainActivity.class}
在 Dagger 1.x 中):
@Singleton
@Component(module={AppContextModule.class}) //this is where you would add additional modules, and a dependency if you want to subscope
public interface ApplicationComponent extends AppContextComponent { //extend to have the provision methods
void inject(MainActivity mainActivity);
}
3.3.)对于您的依赖项can自己通过构造函数创建,并且不想使用重新定义@Module
(例如,您使用构建风格来更改实现类型),您可以使用@Inject
带注释的构造函数。
public class Something {
OtherThing otherThing;
@Inject
public Something(OtherThing otherThing) {
this.otherThing = otherThing;
}
}
另外,如果您使用@Inject
构造函数,您可以使用字段注入而无需显式调用component.inject(this)
:
public class Something {
@Inject
OtherThing otherThing;
@Inject
public Something() {
}
}
These @Inject
构造函数类会自动添加到相同范围的组件中,而无需在模块中显式指定它们。
A @Singleton
scoped @Inject
构造函数类将出现在@Singleton
作用域组件。
@Singleton // scoping
public class Something {
OtherThing otherThing;
@Inject
public Something(OtherThing otherThing) {
this.otherThing = otherThing;
}
}
3.4.)在为给定接口定义特定实现后,如下所示:
public interface Something {
void doSomething();
}
@Singleton
public class SomethingImpl {
@Inject
AnotherThing anotherThing;
@Inject
public SomethingImpl() {
}
}
您需要使用以下命令将特定实现“绑定”到接口@Module
.
@Module
public class SomethingModule {
@Provides
Something something(SomethingImpl something) {
return something;
}
}
自 Dagger 2.4 以来的简写如下:
@Module
public abstract class SomethingModule {
@Binds
abstract Something something(SomethingImpl something);
}
4.)创建一个Injector
类来处理您的应用程序级组件(它取代了整体ObjectGraph
)
(note: Rebuild Project
来创建DaggerApplicationComponent
使用 APT 的构建器类)
public enum Injector {
INSTANCE;
ApplicationComponent applicationComponent;
private Injector(){
}
static void initialize(CustomApplication customApplication) {
ApplicationComponent applicationComponent = DaggerApplicationComponent.builder()
.appContextModule(new AppContextModule(customApplication))
.build();
INSTANCE.applicationComponent = applicationComponent;
}
public static ApplicationComponent get() {
return INSTANCE.applicationComponent;
}
}
5.)创造你的CustomApplication
class
public class CustomApplication
extends Application {
@Override
public void onCreate() {
super.onCreate();
Injector.initialize(this);
}
}
6.) add CustomApplication
给你的AndroidManifest.xml
.
<application
android:name=".CustomApplication"
...
7.)将您的课程注入MainActivity
public class MainActivity
extends AppCompatActivity {
@Inject
CustomApplication customApplication;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Injector.get().inject(this);
//customApplication is injected from component
}
}
8.) Enjoy!
+1.)您可以指定Scope
对于您可以用来创建的组件活动级作用域组件。子范围允许您提供仅针对给定子范围而不是整个应用程序所需的依赖项。通常,每个活动都会通过此设置获得自己的模块。请注意,存在范围内的提供商每个组件,这意味着为了保留该活动的实例,组件本身必须能够承受配置更改。例如,它可以通过onRetainCustomNonConfigurationInstance()
,或迫击炮瞄准镜。
有关子范围的更多信息,请查看谷歌的指南。另请参阅本网站有关提供方法还有组件依赖部分) and here.
要创建自定义范围,您必须指定范围限定符注释:
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface YourCustomScope {
}
要创建子范围,您需要在组件上指定范围,并指定ApplicationComponent
作为它的依赖。显然,您还需要在模块提供程序方法上指定子范围。
@YourCustomScope
@Component(dependencies = {ApplicationComponent.class}, modules = {CustomScopeModule.class})
public interface YourCustomScopedComponent
extends ApplicationComponent {
CustomScopeClass customScopeClass();
void inject(YourScopedClass scopedClass);
}
And
@Module
public class CustomScopeModule {
@Provides
@YourCustomScope
public CustomScopeClass customScopeClass() {
return new CustomScopeClassImpl();
}
}
请注意,仅one作用域组件可以指定为依赖项。就像 Java 中不支持多重继承一样。
+2.) About @Subcomponent
: 本质上是一个范围@Subcomponent
可以替换组件依赖项;但您需要使用组件工厂方法,而不是使用注释处理器提供的构建器。
So this:
@Singleton
@Component
public interface ApplicationComponent {
}
@YourCustomScope
@Component(dependencies = {ApplicationComponent.class}, modules = {CustomScopeModule.class})
public interface YourCustomScopedComponent
extends ApplicationComponent {
CustomScopeClass customScopeClass();
void inject(YourScopedClass scopedClass);
}
就变成这样了:
@Singleton
@Component
public interface ApplicationComponent {
YourCustomScopedComponent newYourCustomScopedComponent(CustomScopeModule customScopeModule);
}
@Subcomponent(modules={CustomScopeModule.class})
@YourCustomScope
public interface YourCustomScopedComponent {
CustomScopeClass customScopeClass();
}
和这个:
DaggerYourCustomScopedComponent.builder()
.applicationComponent(Injector.get())
.customScopeModule(new CustomScopeModule())
.build();
就变成这样了:
Injector.INSTANCE.newYourCustomScopedComponent(new CustomScopeModule());
+3.):请检查有关 Dagger2 的其他 Stack Overflow 问题,它们提供了很多信息。例如,我当前的 Dagger2 结构指定为这个答案.
Thanks
感谢您的指导Github, TutsPlus, 乔·斯蒂尔, 弗罗格MCS and Google.
也为了这个我在写完这篇文章后找到了分步迁移指南。
And for 范围解释由基里尔.
更多信息请参见官方文档.