@Inject不是初始化字段

时间:2017-04-14 08:16:38

标签: android dependency-injection

我第一次学习Dragger2并面临问题跟随是我的类代码。

    public class User {

        private String firstName;
        private String lastName;

        public User(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        @Override
        public String toString() {
            return "User [firstName=" + firstName + ", lastName=" + lastName + "]";
        }
 }

和具有User

依赖关系的BackendService类
public class BackendService {

    @Inject
    public User user;

    private String serverUrl;

    @Inject
    public BackendService(@Named("serverUrl") String serverUrl) {
        this.serverUrl = serverUrl;
    }

    public boolean callServer() {
        if (user !=null && serverUrl!=null && serverUrl.length()>0) {
            System.out.println("User: " + user + " ServerUrl: "  + serverUrl);
            return true;
        }
        return false;
    }

}

和BackEndServiceModule

@Module
public class BackEndServiceModule {

    @Provides
    @Singleton
     BackendService provideBackendService(@Named("serverUrl") String serverUrl) {
        return new BackendService(serverUrl);
    }

    @Provides
    @Singleton
    @Named("serverUrl")
     String provideServerUrl() {
        return "http://www.vogella.com";
    }

    @Provides
    @Singleton
    @Named("anotherUrl")
    String provideAnotherUrl() {
        return "http://www.google.com";
    }
}

和UserModule

@Module
public class UserModule {

    @Provides
    @Singleton
     User providesUser() {
        return new User("James","Peter");
    }
}

和MyComponent

@Singleton
@Component(modules = { UserModule.class, BackEndServiceModule.class})
public interface MyComponent {
    void inject(TestClass activity);
}

我的测试类代码是

public class TestClass {

    @Inject
    BackendService backendService; //

    private MyComponent component;

    public TestClass(){

        component = DaggerMyComponent.builder().build();
        component.inject(this);

        callServer();

    }


    private void callServer() {
        boolean callServer = backendService.callServer();
        if (callServer) {

            Log.v("TestClass","Server call was successful."+backendService.user);
        } else {

            Log.v("TestClass","Server call failed."+backendService.user);
        }
    }
} // this is alway null backendService.user

问题是用户字段在BackendService中始终为null。请指出我在哪里遇到问题。

1 个答案:

答案 0 :(得分:1)

User构造函数中添加BackenService参数,并从@Inject变量中删除User注释

   public User user

    @Inject
    public BackendService(@Named("serverUrl") String serverUrl,User user) {
        this.serverUrl = serverUrl;
        this.user=user
    }

删除BackendService Provider方法

Remove this
@Provides
    @Singleton
     BackendService provideBackendService(@Named("serverUrl") String serverUrl) {
        return new BackendService(serverUrl);
    }