Implications of @Autowired in builder and out

2

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));
    
asked by anonymous 20.06.2017 / 19:11

1 answer

0

All forms serve the same purpose, and you get the same end result. The advantage of being in the constructor is:

  • Explicitly identify which dependencies
  • Dependencies can be end
  • Facilitates the creation of tests. It is easier to inject mocks, you can do this using the class constructor itself, not needing reflection.

Use one or the other is up to you.

    
20.06.2017 / 20:11