2
When working with Spring I realize two patterns of using the @Autowired, declare inside the manufacturer and outside.
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;
}
Construction-free
@Service
public class myService {
@Autowired
PartnerRepository partnerRepository;
@Autowired
RequestorRepository requestorRepository;
//methods
}
What is the use of each case and why prefer one over the other? Personally I have always used outside the constructor only 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 when using in the constructor it is possible to do a direct instantiation with the new.
MyService myService = Mockito.spy(new MyService(partnerRepository, requestorRepository));
There is a third way too, can use the
@Autowired
in a Setter– Denis Rudnei de Souza