java - Spring MVC : difference between <context:component-scan> and <annotation-driven/> tags?

标签 java spring spring-mvc annotations

前几天开始学习这个Spring Hello World教程:http://viralpatel.net/blogs/spring-3-mvc-create-hello-world-application-spring-3-mvc/

在本教程中,Spring DispatcherServlet 是使用 spring-servlet.xml 文件配置的,这个:

<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="net.viralpatel.spring3.controller" />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>

在这个文件中,我使用 context:component-scan 标签来表示 Spring 必须扫描我的文件以搜索注解,例如,当 Controller 类发现一个方法被注解时通过 @RequestMapping("/hello") 注释知道该方法处理向以“/hello”结尾的 URL 的 HTTP 请求。这很简单……

现在我的疑问与我可以在 STS\Eclipse 中自动构建的 Spring MVC 模板项目有关。

当我在 STS 中创建一个新的 Spring MVC 项目时,我的 DispatcherServlet 是由一个名为 servlet-context.xml 的文件配置的,该文件包含一些类似于上一个示例文件。

在这个文件中,我还有组件扫描标签:

<context:component-scan base-package="com.mycompany.maventestwebapp" />

但我还有另一个标签(看起来有类似的任务),这个:

<annotation-driven />

这两个标签有什么区别?
另一个“奇怪”的事情是前面的示例(不使用注释驱动标签)与 STS 使用 Spring MVC 模板项目创建的项目非常相似,但是如果我从其配置中删除注释驱动标签文件项目不运行并给我以下错误:HTTP Status 404 -

在堆栈跟踪中我有:

警告:org.springframework.web.servlet.PageNotFound - 在名为“appServlet”的 DispatcherServlet 中找不到具有 URI [/maventestwebapp/] 的 HTTP 请求的映射

但是为什么呢?前面的例子在没有注释驱动标签的情况下运行良好,这个 Controller 类非常相似。实际上,只有一种方法可以处理对“/”路径的 HTTP 请求

这是我的 Controller 类的代码:

package com.mycompany.maventestwebapp;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
*/
@Controller
public class HomeController {

private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

/**
 * Simply selects the home view to render by returning its name.
 */
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
    logger.info("Welcome home! The client locale is {}.", locale);

    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

    String formattedDate = dateFormat.format(date);

    model.addAttribute("serverTime", formattedDate );

    return "home";
}

有人可以帮我理解这件事吗?

非常感谢!

最佳答案

<mvc:annotation-driven />意味着您可以定义 spring beans 依赖项,而无需实际在 XML 中指定一堆元素或实现接口(interface)或扩展基类。例如 @Repository告诉spring一个类是一个Dao,而无需扩展JpaDaoSupport或 DaoSupport 的其他子类。同样@Controller告诉 spring 指定的类包含将处理 Http 请求的方法,而无需实现 Controller 接口(interface)或扩展实现 Controller 的子类。

当 spring 启动时,它会读取其 XML 配置文件并查找 <bean如果看到类似 <bean class="com.example.Foo" /> 的内容,则其中的元素和 Foo 被标记为 @Controller它知道该类是一个 Controller 并将其视为 Controller 。默认情况下,Spring 假定它应该管理的所有类都明确定义在 beans.XML 文件中。

使用 <context:component-scan base-package="com.mycompany.maventestwebapp" /> 进行组件扫描告诉 spring 它应该在类路径中搜索 com.mycompany.maventestweapp 下的所有类并查看每个类以查看它是否具有 @Controller , 或 @Repository , 或 @Service , 或 @Component如果是这样,那么 Spring 将向 bean 工厂注册该类,就好像您输入了 <bean class="..." />在 XML 配置文件中。

在一个典型的 Spring MVC 应用程序中,你会发现有两个 Spring 配置文件,一个配置应用程序上下文的文件通常以 Spring 上下文监听器启动。

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Spring MVC 配置文件通常以 Spring 调度程序 servlet 启动。例如。

<servlet>
        <servlet-name>main</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>main</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Spring 支持分层 bean 工厂,因此在 Spring MVC 的情况下,调度程序 servlet 上下文是主应用程序上下文的子级。如果向 servlet 上下文询问名为“abc”的 bean,它将首先在 servlet 上下文中查找,如果在其中找不到它,它将在父上下文中查找,即应用程序上下文。

数据源、JPA 配置、业务服务等通用 bean 是在应用程序上下文中定义的,而 MVC 特定配置不是与 servlet 关联的配置文件。

希望这会有所帮助。

关于java - Spring MVC : difference between <context:component-scan> and <annotation-driven/> tags?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13661985/

相关文章:

java - 由于 main 方法不是静态的,编译器错误

java - Java Gradle代码说明findlookupvalues

java - 如何使用注释创建一个包含原型(prototype) bean 实例的列表?

java - tomcat中线程的文件问题

java - HTTP 状态 400 – 错误请求 - Hibernate

java - org.springframework.beans.NotWritablePropertyException : Invalid property 'xxxx' of bean class :

java - 如何回压通过 Activity ?

java - 如何创建具有多个使用相同参数类型的构造函数的类

Spring web 项目在 Eclipse 中与 Tomcat 一起运行正常,但在独立的 ApacheTomcat 服务器上运行时给出 404

java - 如何使用 Java Mongo DB 驱动程序版本 3 将 BasicDBObject 转换为 Mongo 文档?