为什么在Spring中的类上使用@Autowired
我了解了使用接口依赖关系的优点。
我理解接口的概念 - 但为什么要在类上使用@Autowire?如果我们在类上使用 Autowire,我会提前知道实现的类是什么,它就像它的常规成员(无法访问该成员)!
我缺少什么?
I read about the advantages of using Dependency for interface.
I understand the concept for interface - but why to use @Autowire on class? If we use Autowire on class I know in advance what is the implmeneted class and it's like a regular member of it (without the ability of get to this member)!
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
1) 方便 - 你不需要关心初始化你的组件,你可以节省输入代码和配置文件的时间,
2) 强制良好的实践 - 你的要自动装配的组件必须编写为可由 Spring 管理,Spring 会照顾关于为您进行错误检查并弹出所有错误。所以你的代码将以组件协作的方式组织。
3)当您的类/bean 不断增长和发展时,自动装配也将减少您的工作量。
1) Convenience - you do not need to take care for initializing your components, you save time on typing code and configuration files,
2) Forcing good practices - your components to be autowired must be written to be manageable by Spring and spring will take care about error checking for you and pop all errors. So your code will be organized in component collaborating way.
3) Autowiring will also reduce your effort when your classes/beans will grow and evolve.
如果您使用 @Autowire 且不调用构造函数,则将该类标记为由 Spring 容器动态初始化。这允许您设置 spring 配置中定义的类属性。
If you use
@Autowire
and not call the constructor, you mark the class to be dynamically initialized by the Spring Container. This allows you to set class properties as defined in your spring configuration.当您通过 XML 而不是注释连接依赖项时,您还可以提前知道要在哪个类中注入它。
但是您仍然将接口声明为依赖项,因此您可以在运行时连接该接口的任何实现。
When you wire the dependency through XML instead of Annotations, you also know in advance in which class are you going to inject it.
But You still declare an Interface as dependency, so you can wire any Implementation of this interface at runtime.