When working with Spring I notice two patterns of using the @Autowired , declare inside the constructor and out.
Builder
@Service
public class myService {
private final PartnerRepository partnerRepository;
private final RequestorRepository requestorRepository;
@Autowired
public myService(PartnerRepository partnerRepository, RequestorRepository requestorRepository) {
this.partnerRepository = partnerRepository;
this.requestorRepository = requestorRepository;
}
No builder
@Service
public class myService {
@Autowired
PartnerRepository partnerRepository;
@Autowired
RequestorRepository requestorRepository;
//methods
}
What is the use of each case and why do you prefer one instead of the other? Personally I've always used outside the constructor just to look more elegant.
The only direct implication I noticed was for unit tests with Mockito and JUnit, when using outside the constructor it is necessary to use @Spy (response in SOen ) and using it in the constructor it is possible to do a direct instantiation with new .
MyService myService = Mockito.spy(new MyService(partnerRepository, requestorRepository));