gpt4 book ai didi

java - 注解Spring @Controller也作为Bean?

转载 作者:行者123 更新时间:2023-12-01 06:47:35 25 4
gpt4 key购买 nike

带注解的 Spring MVC Controller 是否也可以使用 @Component/@Service 类型的注解进行注解,并且既可以用作 Controller ,也可以用作 bean?

最佳答案

编辑:更加重视软件设计方面,并将 API 链接更新为 SpringV3

正如其他答案中提到的,这不是 Spring MVC 的理想方法,但尽管如此, Controller 已经可以在您的 ApplicationContext 中进行 Autowiring 。

它已经是您的 ApplicationContext 中的一个 Bean,因此您可以按类型 Autowiring 它。无需添加@Component注释。

摘自 Spring API 文档:“此注释作为 @Component 的特化,允许通过类路径扫描自动检测实现类。”

http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/stereotype/Controller.html

@Service 也是如此。

虽然我自己做过,但我通常不会推荐这种设计方法。

如果可能,将所需的功能重构为一个单独的 bean,然后根据需要将其(自动)连接到 @Controller 和任何其他 bean。

如果,正如您所评论的,您被“逼入绝境”做出这个决定(就像我一样,被之前的设计选择所困扰),那就这样吧。

HTH

关于java - 注解Spring @Controller也作为Bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5863289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com