spring基本的mvc示例应用,注释扫描混乱

Bla*_*man 7 spring annotations spring-mvc

有点困惑,基本的春季mvc应用程序有这个:

APP-config.xml中

<context:component-scan base-package="org.springframework.samples.mvc.basic" />
Run Code Online (Sandbox Code Playgroud)

并且mvc-config.xml具有:

<!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />
Run Code Online (Sandbox Code Playgroud)
  1. 你真的需要两个吗?

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

我尝试只使用mvc:annotation-driven但是没有用,我不得不将com.example.web.controllers放在component-scan xml节点中以使其工作.

Art*_*ald 11

上下文:组件扫描很清楚

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

所以@Controller只是一个Spring bean.没有其他的.

MVC:注解驱动

注册将调用请求发送到@Controllers所需的HandlerMapping和HandlerAdapter

这是类似的

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
Run Code Online (Sandbox Code Playgroud)

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

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

<context:component-scan base-package="br.com.app.view.controller"/>
<context:component-scan base-package="br.com.app.service"/>
Run Code Online (Sandbox Code Playgroud)

要么

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

<context:component-scan base-package="br.com.app.view.controller,br.com.app.service"/>
Run Code Online (Sandbox Code Playgroud)