g3blv
g3blv

Reputation: 4377

Spring Boot Constructor based Dependency Injection

I'm a beginner with Spring Boot and Dependency Injection and I can't get my head around Constructor based Dependency Injection in Spring Boot. I have class called ParameterDate that look like this:

public class ParameterDate {

    private Date parameterDateUnadjusted;
    private Date parameterDateAdjusted;
    private Date parameterDateAdded;
    private Date parameterDateChanged;
}

I have another class where I want to use ParameterDate. Normally I would do Field based Injection with

@Autowired
ParameterDate parameterDate;

And where ever needed I just use parameterDate.

How would I do this with Constructor based Injection?

Upvotes: 11

Views: 29438

Answers (2)

Darren Forsythe
Darren Forsythe

Reputation: 11411

public MyClazzRequiringParameterDate(ParameterDate parameterDate){
     this.parameterDate = parameterDate;
}

Since Boot 1.4 @Autowired has been optional on constructors if you have one constructor Spring will try to autowire it. You can just tag the constructor with @Autowired if you want to be explicit about it.

Generally speaking you should favour Constructor > Setter > Field injection. Injecting directly to the field misses the point of DI, it also means your tests are reliant on Spring to inject dependencies into rather than just being able to pass mocks or stubs directly to it. Jurgan Holler has stated that he would remove field injection if at all possible.

Upvotes: 25

Sabina Orazem
Sabina Orazem

Reputation: 487

@Component    
public class ParameterDate {

    private Date parameterDate;

@Autowired
public ParameterDate(Date parameterDate){
this.parameterDate = parameterDate;
}
}

Above is an example of constructor injection.

Note that you can use @Autowired annotation also on property's setter method, and since there is no difference between setter method (except of course it's purpose, logic it contains) and any other method, you can use @Autowired on just about any method of the class. Since autowiring and component scanning go hand in hand, you should mark your class with @Component annotation. This tells Spring that a bean should be created for this class.

Upvotes: 2

Related Questions