module
一个类似工厂的类。
@Module
public class ApplicationModule {
}
需要被包含到component中才能起作用。通过Component的modules属性赋值。
@Component(modules = {ApplicationModule.class})
public interface ApplicationComponent {
void inject(MyApp app);
User user();
}
如上,我们需要在接口ApplicationComponent 中获取到User,或者在MyApp中注入User。
public class MyApp extends Application {
@Inject
User user;
@Override
public void onCreate() {
super.onCreate();
DaggerApplicationComponent.create().inject(this);
}
}
可以通过在User的构造函数上标注Inject实现。
public class User {
@Inject
public User(){
}
}
也可以通过在module的方法上标注Providers实现。这种方式的优先级高于inject标注构造函数的优先级。
@Module
public class ApplicationModule {
@Provides
User user() {
return new User();
}
}
成功编译后的Dagger类。
@Generated("dagger.internal.codegen.ComponentProcessor")
public final class DaggerApplicationComponent implements ApplicationComponent {
private Provider<User> userProvider;
private MembersInjector<MyApp> myAppMembersInjector;
private DaggerApplicationComponent(Builder builder) {
assert builder != null;
initialize(builder);
}
public static Builder builder() {
return new Builder();
}
public static ApplicationComponent create() {
return builder().build();
}
private void initialize(final Builder builder) {
this.userProvider = ApplicationModule_UserFactory.create(builder.applicationModule);
this.myAppMembersInjector = MyApp_MembersInjector.create((MembersInjector) MembersInjectors.noOp(), userProvider);
}
@Override
public void inject(MyApp app) {
myAppMembersInjector.injectMembers(app);
}
@Override
public User user() {
return userProvider.get();
}
public static final class Builder {
private ApplicationModule applicationModule;
private Builder() {
}
public ApplicationComponent build() {
if (applicationModule == null) {
this.applicationModule = new ApplicationModule();
}
return new DaggerApplicationComponent(this);
}
public Builder applicationModule(ApplicationModule applicationModule) {
if (applicationModule == null) {
throw new NullPointerException("applicationModule");
}
this.applicationModule = applicationModule;
return this;
}
}
}
实质是根据传入的module创建了一个工厂类。
@Generated("dagger.internal.codegen.ComponentProcessor")
public final class ApplicationModule_UserFactory implements Factory<User> {
private final ApplicationModule module;
public ApplicationModule_UserFactory(ApplicationModule module) {
assert module != null;
this.module = module;
}
@Override
public User get() {
User provided = module.user();
if (provided == null) {
throw new NullPointerException("Cannot return null from a non-@Nullable @Provides method");
}
return provided;
}
public static Factory<User> create(ApplicationModule module) {
return new ApplicationModule_UserFactory(module);
}
}
Component接口获取的实例就是工厂类的get方法返回的实例,工厂类返回的实质上是module里的方法返回的实例。注入的实例也是这样来的。