我正在尝试学习Dagger2,但模块即将推出。 我正在关注http://www.vogella.com/tutorials/Dagger/article.html的教程 这是我的代码如下。
public class TestApp {
@Inject
BackendService backendService;
private void testServer() {
BackendComponent backendComponent = DaggerBackendComponent.builder()
.build();
backendComponent.inject(this);
backendService.call();
}
public static void main(String[] args) {
new TestApp().testServer();
}
}
注入不起作用的UserModule
@Module
public class UserModule {
@Provides
@Singleton
User providesUser() {
return new User("John", "Doe");
}
}
BackendService
public class BackendService {
@Inject
public User user;
private String serverUrl;
@Inject
public BackendService(@Named("serverUrl") String serverUrl) {
this.serverUrl = serverUrl;
}
public boolean call() {
if (user != null && serverUrl != null && serverUrl.length() > 0) {
System.out.println("User: " + user.toString());
return true;
} else {
System.err.println("User: " + user);
System.err.println("ServerUrl: " + serverUrl);
return false;
}
}
}
BackendServiceModule
@Module
public class BackendServiceModule {
@Provides
@Singleton
BackendService proviedBackendServiceModule(@Named("serverUrl") String serverUrl) {
return new BackendService(serverUrl);
}
@Provides
@Named("testUrl")
String provideAnotherUrl() {
return "http://www.facebook.com";
}
@Provides
@Named("serverUrl")
String provideServerUrl() {
return "http://www.google.com";
}
}
BackendComponent
@Singleton
@Component(modules = {UserModule.class, BackendServiceModule.class})
public interface BackendComponent {
BackendService proviedBackendServiceModule();
void inject(TestApp app);
}
运行后我得到如下输出:
User: null
ServerUrl: http://www.google.com
如果我尝试按照代码运行
public class TestApp {
@Inject
User user;
@Inject
BackendService backendService;
private void testServer() {
BackendComponent backendComponent = DaggerBackendComponent.builder()
.build();
backendComponent.inject(this);
backendService.call();
System.out.println("User: " + user);
}
public static void main(String[] args) {
new TestApp().testServer();
}
}
User: null
ServerUrl: http://www.google.com
User: User [firstName=John, lastName=Doe]
答案 0 :(得分:1)
你的问题的原因是匕首的工作方式。它只会在您指定为注入方法参数的类上注入使用@Inject注释的字段。因此,注入@Inject注释的BackendService内部不会被注入。
public class TestApp {
@Inject <-- this is injected
User user;
@Inject <-- this is injected
BackendService backendService; <-- Nothing inside this class will be injected
我建议将您的用户对象传递给构造函数中的BackendService。做这样的事情:
@Provides
@Singleton
BackendService proviedBackendServiceModule(@Named("serverUrl") String serverUrl, User user) {
return new BackendService(serverUrl, user);
}
另一个解决方案是为组件内部的BackendService定义一个注入方法,但是它会在组件对象周围乱七八糟。