I’ve been developing in Spring Boot for just over a year but have yet to understand the benefits of using an Autowired constructor and I was wondering if someone could explain this to me and what would be considered best practice.
Let’s say I have a bean as follows
@Component
public class MyBean {
void doSomeStuff() {
}
}
And I have a service that has a dependency on that bean
@Service
public class MyServiceImpl implements MyService {
private MyBean myBean;
}
To me, the simplest way of injecting the dependency in this class would be to simply annotate the variable with @Autowired
@Service
public class MyServiceImpl implements MyService {
@Autowired
private MyBean myBean;
}
But there are other places online (and also other developers on my team) who favour something like this approach:
@Service
public class MyServiceImpl implements MyService {
private MyBean myBean;
@Autowired
public MyServiceImpl(MyBean myBean) {
this.myBean = myBean;
}
}
To me, using a constructor like that is simply redundant code. Autowiring the bean is much simpler and straightforward than what appears to me to be boilerplate code.