Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 981
g3blv Avatar asked Jun 04 '17 17:06

g3blv


1 Answers

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.

like image 157
Darren Forsythe Avatar answered Nov 09 '22 07:11

Darren Forsythe