Вопрос

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.

Это было полезно?

Решение

You use a real constructor for the same reasons that you use public getters and setters instead of making private variables public.

Some real-life examples: cell phones are not allowed in secure, information-sensitive physical locations. Any communication with that secure location must take place through a securely-established, controlled and encrypted communications protocol, not surreptitously by an unmonitored and uncontrolled rogue communications channel.

At a concert, you don't allow people to throw things over the fence to someone who's already in the stadium. Anything coming in or out must go through a gate.

If that's all there is to your code example, then it does appear like unnecessarily verbose boilerplate. But frequently we do other things in the constructor besides setting private variables, like validation. In many programming languages, changing the way you do this after the fact is a binary breaking change, so providing the constructor up front can be a sensible step.

Finally, the class should be able to function independently of the dependency injection. If you put an annotation on a private member, but fail to include a constructor, you've essentially tightly-bound that class to the DI container, and the class won't work without it.

Лицензировано под: CC-BY-SA с атрибуция
scroll top