Search code examples
javadependency-injectionguice

Proper way of injecting dependencies?


Which one is the best way of injecting my dependencies? Why? What is the difference between the two?

public abstract class Service {

    private IConfig config;

    @Inject
    public Service(IConfog config) {
        this.config = config
    }
}

Or

public abstract class Service {

    @Inject private IConfig config;

    @Inject
    public Service() {

    }
}

Solution

  • Constructor injection (1st) is preferred over setter injection given that it makes it easier to support "immutable" entities or entities whose behaviour is well defined and non-modifiable after construction. Constructor vs Setter inject

    For me the rule of thumb is to first prefer constructor injection and jump off to setter injection if constructor inject requires me to bend my back i.e. when working with legacy code with "OOP getter and setter" methods.

    EDIT: I'm assuming you are trying to decide between "constructor" and "setter" constructor. But it also seems that you are using abstract classes which can't be instantiated. Maybe you have something else in mind?