abd3lraouf
abd3lraouf

Reputation: 1658

Dagger2 can't inject field inside injected class

I was trying to playaround with dagger2 but I got problems with field injection, and here is my code.

POJO classes :

// User.java
public class User {
    private String firstName, lastName;
    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

The class which I can't inject the user field.

//BackendService.java
public class BackendService {
    @Inject
    public User user; // Not injected -> Null

    @Inject
    public BackendService() {
    }
}

User provider class

// UserModule.java
@Module
public class UserModule {

    @Provides
    @Singleton
    User providesUser() {
        return new User("AA","BB");
    }
}

Backend provider class

// BackendServiceModule.java
@Module
public class BackendServiceModule {
    @Provides
    BackendService provideBackendService() {
        return new BackendService();
    }    
}

And last but not least, the component

// ApplicationComponent.java
@Component(modules = {UserModule.class, BackendServiceModule.class})
public interface ApplicationComponent {
    BackendService provideBackendService();
    void inject(ConsumerMain consumerMain);
}

The problem is that in BackendService.java the field user doesn't get injected.

Injection is working properly on BackendService

Upvotes: 1

Views: 1360

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95634

Delete your @Provides BackendService method.

When you call new BackendService(), you're telling Dagger "don't worry about how to create a BackendService, I can do it for you". That also prevents Dagger from calling @Inject-annotated constructors and methods, or populating @Inject-annotated fields.

When you delete that method, Dagger will inspect BackendService to learn how to instantiate it itself, at which point it will see your @Inject constructor and field and use them to construct a BackendService when needed.

Upvotes: 4

Related Questions