【问题标题】:I cannot get a Restcontroller included in Spring Boot project - error 404我无法在 Spring Boot 项目中包含 Restcontroller - 错误 404
【发布时间】:2019-04-26 14:42:58
【问题描述】:

Spring Boot 上的新手 pb,我无法将 RestController 添加到我的应用程序中。

以下是用于使用 maven 构建这个非常简单的应用程序的 2 个文件:

1) Application.java

package com.learn.hello;

import java.util.Arrays;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


@Configuration
@ComponentScan(basePackages = "com.learn.hello.controller")
@RestController
@SpringBootApplication
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@RequestMapping("/")
    public String index() {
    return "Greetings from Spring Boot!";
}
}

HelloController.java

package com.learn.hello.controller;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
public class HelloController {

@RequestMapping("/titi")
public String index() {
    return "Greetings from titi Boot!";
}

}

项目结构

/src/main/java/com/learn/hello/Application.java
/src/main/java/com/learn/hello/controller/HelloController.java
/target/*
/pom.xml

localhost:8080 有效

但 localhost:8080/titi 没有(404 未找到)

有什么想法吗? 谢谢

【问题讨论】:

  • 你能显示你的启动日志吗?
  • 你忘记提供请求方法 RequestMethod.GET : @RequestMapping(value = "/students", method = RequestMethod.GET) 你可以使用@GetMapping("/titi") 代替@RequestMapping(" /titi")
  • 从 Application 类中移除 @restcontroller 和 ComponentScan
  • 这太奇怪了,一切似乎都很好,我唯一能做的就是删除@ComponentScan,因为它已经包含在@SpringBootApplication 中的控制器已经执行了/Application 的@ComponentScan。 java /src/main/java/com/**
  • 重复它太奇怪了,我测试了同样的你的类,在我的本地环境中它的工作! perapsh 您的问题出在其他地方,请分享有关您项目的更多详细信息

标签: spring spring-boot


【解决方案1】:

您忘记提供请求方法 RequestMethod.GET :

@RequestMapping(value = "/students", method = RequestMethod.GET)

您可以使用@GetMapping("/titi") 代替@RequestMapping("/titi") :

@GetMapping("/titi")

【讨论】:

    【解决方案2】:

    感谢大家的回答。

    @瓦莱里奥, 你是对的,这是正确的!!!事实上,在文件名的末尾添加了一个不可见的字符:HelloController.java(我可能搞砸了 Sublime ......),因此它没有被 maven 处理为 java 文件......

    抱歉打扰了。我很抱歉。

    顺便说一句,如果有人知道任何类型的选项来实际警告位于 /src/main/java/* 目录中的文件未作为“常规 java 项目”文件处理,我什至有兴趣了解它虽然我怀疑这是否真的可行并因此存在......

    【讨论】:

      猜你喜欢
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      相关资源
      最近更新 更多