java - 为什么 Spring RequestMapping 没有 @Controller 就无法工作?

标签 java xml spring

我有示例代码:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">

    <servlet>
        <servlet-name>springDispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>springDispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

springDispatcher-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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    <bean id="myController" class="biz.tugay.springWebOne.MyController"/>
</beans>

MyController.java

package biz.tugay.springWebOne;
/* User: koray@tugay.biz Date: 08/07/15 Time: 15:25 */

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {
    @RequestMapping(value = "/hello")
    public String helloWorld(){
        return "index.jsp";
    }
}

嗯,这段代码一切正常。但是当我删除

 @Controller

MyController 类我将得到:

HTTP ERROR 404

Problem accessing /hello. Reason:

    Not Found

我没有使用组件扫描,我使用的是基于 xml 的配置。为什么需要 @Controller 注解?

最佳答案

来自 spring 引用文档 here

The @Controller annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotations

因此,@Controller需要告诉调度程序扫描此类中的映射,而不仅仅是组件扫描。

关于java - 为什么 Spring RequestMapping 没有 @Controller 就无法工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31294068/

相关文章:

xml - 如何有效地在 XML 中建模逻辑/ bool 表达式?

java - Spring MVC Portlet 操作映射不起作用

java - HttpServletRequest 详细信息使用 @Async Spring 返回 null

java - jpa中多对多关系中间表中的附加列

java - JTable 中的 JButton 单击时不显示动画

java - 可调整大小的 Java 组件

java - 使用 Flyway 应用程序与 Pax Exam 集成来测试 OSGi 应用程序

java - 使用 Spring Boot 进行集成测试

java - 如何在 Java 中解析带有 "Opening and ending tag mismatch"的 XML 文件

xml - Clojure 应用程序数据交换