我正在嘗試學習Dagger2,但模塊即將推出,因爲已棄用。 我從以下教程http://www.vogella.com/tutorials/Dagger/article.html 這是我的代碼如下。Dagger2模塊未注入其他模塊或已棄用
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]
請提供BackendComponent的代碼。 – Jacob
@Jacob我已經添加了BackendComponent代碼,請檢查。 – sector11