【问题标题】:spring basic mvc sample application, annotation scan confusionspring基本mvc示例应用,注解扫描混淆
【发布时间】:2010-07-01 01:34:26
【问题描述】:

有点迷茫,基本的spring mvc app有这个:

app-config.xml

<context:component-scan base-package="org.springframework.samples.mvc.basic" />

并且 mvc-config.xml 有:

<!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />
  1. 你真的需要两者吗?

  2. 对于组件扫描,这是否意味着如果我没有放置正确的包路径,我的 @Controller 和 @Service 标记将不起作用? 如果我需要多个包裹,是否只需复制条目?

我尝试只使用 mvc:annotation-driven 但这不起作用,我必须将 com.example.web.controllers 放在组件扫描 xml 节点中才能使其工作。

【问题讨论】:

    标签: spring spring-mvc annotations


    【解决方案1】:

    context:component-scan 很清楚

    扫描类路径中的注释组件,将自动注册为 Spring bean默认情况下,将检测 Spring 提供的 @Component、@Repository、@Service 和 @Controller 构造型。

    所以@Controller 只是一个 Spring bean。没有别的了。

    mvc:annotation-driven

    注册 HandlerMapping 和 HandlerAdapter 所需的将请求分发到您的@Controllers

    类似于

    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
    

    如果我需要多个包裹,是否只需复制条目?

    如果你愿意,你可以。 context:component-scan 只是一个 bean 后处理器

    <context:component-scan base-package="br.com.app.view.controller"/>
    <context:component-scan base-package="br.com.app.service"/>
    

    或者

    使用逗号分隔的包列表来扫描带注释的组件。

    <context:component-scan base-package="br.com.app.view.controller,br.com.app.service"/>
    

    【讨论】:

    • 只是为了好奇:context:component-scan 包括 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor 这意味着这两个组件是自动检测并连接在一起的 - 所有这些都没有在 XML 中提供任何 bean 配置元数据
    • 谢谢,我不想做 br.com.app 因为它可能会扫描比需要更多的类。很好的答案!顺便说一句,@component 和 @service 之间的区别是什么?
    • @Blankman 无。 @Service 也是一个 @Component 注解。见这里:static.springsource.org/spring/docs/2.5.6/api/org/…它只是一个特殊的元数据,用于表示服务层中的服务组件
    【解决方案2】:
    1. mvc:annotation-driven 允许您配置 Spring MVC 的行为。请参阅documentation 中的详细信息。对于 Spring MVC 的基本用法,您不需要它。
    2. 如果您需要多个包,只需提及父包:&lt;context:component-scan base-package="org.springframework.samples.mvc" /&gt;

    【讨论】:

    猜你喜欢
    • 2018-12-10
    • 2015-11-17
    • 2011-07-05
    • 2012-05-19
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多