Spring Boot 中的 API 调用出现 404 错误

Ana*_*ary 5 java spring http-status-code-404 spring-boot

我正在开发一个 Spring Boot 应用程序。我在点击我配置的 URL 路径时收到404 错误。我哪里错了?

主控制器.java

package com.example.homes;

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

@RestController("/add")
public class HomeController {

    @GetMapping("/hello")
    public String add() {
        return "Hello";
    }

}
Run Code Online (Sandbox Code Playgroud)

主页应用程序.java

package com.example.homes;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

@SpringBootApplication
public class HomeApplication {

    public static void main(String[] args) {
        SpringApplication.run(HomeApplication.class, args);
        System.out.println("Inside main");
    }

}
Run Code Online (Sandbox Code Playgroud)

SMa*_*MaZ 7

您缺少 的 RequestMapping /add。你保留为@RestController财产。它应该是@RequestMapping("/add")。在您当前的代码中hello映射到根。

尝试一下 localhost:8080/hello,它会起作用的。

如果你想localhost:8080/add/hello

那么它应该像下面这样:


@RestController
@RequestMapping("/add")
public class HomeController {

    @GetMapping(value = "/hello") 
    public String add() {
        return "Hello";
    }
}
Run Code Online (Sandbox Code Playgroud)