在Spring中将daos注入到服务中、将服务注入到控制器中最合适的方式是什么?
Spring框架中有很多注释,如@Component、@Service、@Repository、@Service @Resource和@Autowired等。
在服务中注入我的daos以及在Spring控制器中注入我的服务类的最合适的方式是什么。
有了如此多的注释,它变得令人困惑,尤其是 @Autowired 适用于所有情况。
There are many annotations in the Spring framework like @Component, @Service, @Repository, @Service @Resource and @Autowired etc.
What is the most appropriate way of injecting my daos in services, and my service class in the Spring Controller.
With so many annotations it is getting confusing especially with @Autowired working for all situations.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
@Service
和@Repository
只是@Component
的“子注释”,用于更多地指定 bean(将服务与存储库分开)更复杂的东西)。从注入的角度来看,这三者是相等的。对于注入来说,有3种:
@Resource
@Inject
@Autowired
@Autowired
是最强大的注解,但是@Resource
(JSR-250) 和@Inject
(JSR-330) 已标准化。 — 无论如何,如果您不打算在非 Spring 环境中重用您的应用程序,那么我不会太关注这个问题。@Service
and@Repository
are just "sub-annotations" for@Component
to specify the bean a bit more (to separete Services from Repositories for more sophisticated stuff). From the point of injection this three are equal.For injection, there are 3:
@Resource
@Inject
@Autowired
@Autowired
is the most powerful annotation, but@Resource
(JSR-250) and@Inject
(JSR-330) are standardized. — Anyway if you not plan to reuse your application in a non-Spring environment, then I would not pay to many attention to this concern.请参阅 Spring 中基于注解的配置,对我来说最好的
Spring Annotation
教程。See Annotation based configuration in Spring, best
Spring Annotation
tutorial for me.我更喜欢避免注释,尤其是当它们开始变得混乱时。在这种情况下,好的旧 getter 和 setter 没有任何问题。只需要自己连接 bean,这并不困难,以至于需要注释。
I prefer to avoid annotations, especially if they start getting confusing. Nothing wrong with good old getter and setters in this case. Just gotta wire the bean on your own, which isn't so difficult that annotations are necessary.