gpt4 book ai didi

spring - 不同的 Spring 注解 XML 声明

转载 作者:行者123 更新时间:2023-12-01 02:41:55 25 4
gpt4 key购买 nike

似乎有多个 XML 标记用于告诉 Spring 使用注释:

<context:annotation-config/>

<context:component-scan base-package="org.example" />

<mvc:annotation-driven />

<tx:annotation-driven transaction-manager="transactionManager" />

我认为第一个标签说要扫描注释,第二个标签说要扫描哪个包(并且可以选择排除/包含要搜索的内容)。然后也许第三个说扫描 Controller 类。最后一个扫描数据访问注释。

我的问题理解是:
  • 我认为标签 1 和 2 可以合并为一个。所以我不知道他们为什么分开。
  • 标签 3 和 4 对 1 和 2 来说似乎是多余的。

  • 谁能告诉我每个标签的作用,以及为什么它们不是多余的?如果还有其他注释 XML 标签,请告诉我。

    编辑

    经过进一步调查,我相信我发现了一些额外的信息:
  • <context:annotation-config/>标签允许您在变量、构造函数和方法(例如@Autowired、@Resource 等)上使用注释。
  • <context:component-scan base-package="org.example" />标签允许您在类上使用注释(例如@Repository、@Controller 等)。
  • <tx:annotation-driven transaction-manager="transactionManager" />标签实际上 启用 @Transactional 标签(<context:annotation-config/> 标签允许@Transactional 标签,但它没有 任何事情)。

  • 仍然不能完全确定 <mvc:annotation-driven /> .我想也许它增加了对 JSON 等的进一步支持。

    最佳答案

  • annotation-config 之间的区别和 component-scan
    一)<context:annotation-config/>仅在定义它的同一应用程序上下文中查找 bean 上的注释。这意味着,如果你把 <context:annotation-config/>在 DispatcherServlet 的 WebApplicationContext 中,它仅检查 Controller 中的 @Autowired bean,而不检查您的服务。见部分 15.2, “The DispatcherServlet”了解更多信息。

    b) Spring 提供了自动检测“原型(prototype)”类并使用 ApplicationContext 注册相应 BeanDefinition 的能力。要自动检测这些类并注册相应的 bean,需要包含 component-scan XML 中的元素,其中“basePackage”将是一个公共(public)父包(或者可以指定一个逗号分隔的列表,其中包括每个类的父包)。
  • tx:annotation-driven
    您确实直接在元素中提供了事务管理器实例。 annotation-configcomponent-scan惯于。
  • mvc:annotation-driven
    此标记注册 Spring MVC 将请求分派(dispatch)到 @Controllers 所需的 DefaultAnnotationHandlerMapping 和 AnnotationMethodHandlerAdapter bean。该标记根据类路径中存在的内容为这两个 bean 配置合理的默认值。阅读更多 Spring doc .
  • 关于spring - 不同的 Spring 注解 XML 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8038830/

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