开发者

Autowiring vs instantiating in Spring

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 by spring or just use class instances

in case when I have only one implementation of that interface?

F开发者_如何学Pythonor example:

@Controller

public class MyController {
    @Autowired
    MyService myService;

    @RequestMap("/")
    public String mainPage() {
        ...
    }
}

or

@Controller

public class MyController {
    @RequestMap("/")
    public String mainPage() {
        MyService myService = new MyServiceImpl();
        ...
    }
}

if there is only one implementation of MyService interface?


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜