Autowiring vs instantiating in Spring

后端 未结 2 534
春和景丽
春和景丽 2021-01-22 17:34

I\'ve started to use Spring recently. And I\'m making spring mvc project. So my question is if it\'s preferred to make interfaces and autowire it with particular implementation

相关标签:
2条回答
  • 2021-01-22 17:37

    It will depend on whether MyService is a bean that holds a state or not. If MyService does not hold state, then you don't need to create new instances and you can let Spring to inject it having the advantages above described

    0 讨论(0)
  • 2021-01-22 17:50

    In most cases you should go with injection because:

    • It eases unit testing (you can inject mock or different implementation)
    • Spring can inject some dependencies into MyServiceImpl as well because it manages this object
    • You are not coupling your controller with particular implementation

    Even if your service does not have an interface, because of the second reason you should consider injection.

    The only case when you might want to skip Spring is when the class does not have any dependencies and is stateless. But most likely such a class is a utility that does not need any an instance at all because it has only static members.

    0 讨论(0)
提交回复
热议问题