Implications of @Autowired on and off

Asked

Viewed 525 times

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));
  • 1

    There is a third way too, can use the @Autowired in a Setter

1 answer

0

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

  • Explicitly identify which dependencies
  • The dependencies can be final
  • Makes it easier to create tests. It’s easier to inject mocks, you can do this using the class constructor itself, not needing reflection.

Use one or the other is in your choice.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.