在Spring中自动装配与实例化 [英] Autowiring vs instantiating in Spring
问题描述
我最近开始使用Spring.而且我正在做Spring MVC项目.因此,我的问题是,是否更愿意在春季之前通过特定的实现来制作接口并将其自动布线,还是仅在使用类实例的情况下使用该类实例?
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?
例如:
@Controller
public class MyController {
@Autowired
MyService myService;
@RequestMap("/")
public String mainPage() {
...
}
}
或
@Controller
public class MyController {
@RequestMap("/")
public String mainPage() {
MyService myService = new MyServiceImpl();
...
}
}
如果只有MyService接口的一种实现?
if there is only one implementation of MyService interface?
推荐答案
在大多数情况下,您应该进行注射,因为:
In most cases you should go with injection because:
- 它简化了单元测试(您可以注入模拟或其他实现)
- Spring也可以将某些依赖项注入到
MyServiceImpl
中,因为它可以管理此对象 - 您没有将控制器与特定的实现方式耦合
- 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.
您可能要跳过Spring的唯一情况是该类没有任何依赖关系并且是无状态的.但是此类很可能是一个实用工具,因为它只有static
个成员,因此根本不需要任何实例.
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.
这篇关于在Spring中自动装配与实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!