注解Spring @Controller也作为Bean?
带注释的 Spring MVC 控制器是否也可以使用 @Component/@Service 类型的注释进行注释,并且既可以用作控制器也可以用作 bean?
Can an annotated Spring MVC Controller also be annotated with @Component/@Service type of annotations and be used both as a controller and as a bean?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编辑:更加重视软件设计方面,并将 API 链接更新为 SpringV3
正如其他答案中提到的,这不是 Spring MVC 的理想方法,但尽管如此,控制器已经可用于在您的 ApplicationContext 中自动装配。
它已经是您的 ApplicationContext 中的一个 Bean,因此您可以按类型自动装配它。无需添加 @Component 注释。
来自 Spring API 文档:“此注释充当 @Component 的特化,允许通过类路径扫描自动检测实现类。”
http://static.springsource.org /spring/docs/3.0.x/api/org/springframework/stereotype/Controller.html
@Service 也是如此。
虽然我自己做过,但我通常不会推荐这种设计方法。
如果可能,将所需的功能重构为单独的 bean,然后根据需要将其(自动)连接到 @Controller 和任何其他 bean。
如果,正如您所评论的,您被“逼入绝境”做出这个决定(就像我一样,由于之前的设计选择),那就这样吧。
华泰
Edit: placing more emphasis on the software design aspect, and updating the API link to SpringV3
As mentioned in other answers, this is not an ideal approach to Spring MVC, but nevertheless the controller will already be available for autowiring in your ApplicationContext.
It's already a Bean in your ApplicationContext, so you can auto-wire it by type. There's no need to add an @Component annotation.
From the Spring API Docs: "This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning."
http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/stereotype/Controller.html
The same holds true for @Service.
Although I've done it myself, I would not normally recommend this design approach.
If possible, refactor the required functionality into a separate bean, which can then be (auto-)wired into both the @Controller, and any other bean, as required.
If, as you have commented, you are 'cornered' into this decision (as I was, by previous design choices), then so be it.
HTH
它可以,但不应该。 Web 控制器应该是一个入口点,仅此而已。
它执行的任何可重用逻辑都应该位于专用的服务层中,而不是在控制器本身中
It can but it shouldn't. A web controller should be an entry point, nothing else.
Any reusable logic it performs should be in a dedicated service layer, not in the controller itself
不,听起来好像做得太多了。两者之一,而不是两者。我不知道这是否可能(我对此表示怀疑),但我确信这是不可取的。
No, sounds like it's doing too much. One or the other, not both. I don't know if it's possible (I doubt it), but I'm sure it's not advisable.
我认为你应该更多地了解前端控制器、MVC、DAO 和多层架构等模式。
I think that you should hear more about patterns like Front Controller, MVC, DAO and Multitier architecture and so on.