Spring Boot 为什么在创建新类时RestController不工作

ruoxqz4g  于 2023-03-02  发布在  Spring
关注(0)|答案(3)|浏览(181)

我有一个主类,在其中使用了RestController,它工作得很好

package dev.rizwan.movieapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class MoviesApplication {

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

    @GetMapping("/")
    public String apiRoot() {
        return "This is the root of API";
    }
}

当我转到localhost:8080时,它显示"这是API的根"
我创建了另一个类

package dev.rizwan.movieapi;

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

@RestController
@RequestMapping("/api/v1/movies")
public class MovieController {

    @GetMapping
    public String getAllMovies () {
        return "All Movies";
    }
}

但是当我转到localhost:8080/api/v1/movies时,它显示白标签错误页面
请帮帮我...
我本来期待它显示"所有电影"当我去localhost:8080/api/v1/movies

w46czmvw

w46czmvw1#

希望这起作用了:
只需更改以下内容:

@RestController
@RequestMapping("/api/v1/movies")
public class MovieController {

    @GetMapping
    public String getAllMovies () {
        return "All Movies";
    }
}

与:

@RestController
@RequestMapping("/api/v1")
public class MovieController {

    @GetMapping("/movies")
    public String getAllMovies () {
        return "All Movies";
    }
}
q8l4jmvw

q8l4jmvw2#

在主类中你需要做一些改变。

package dev.rizwan.movieapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@ComponentScan(basePackages = {"dev.rizwan.movieapi"}) // added
public class MoviesApplication {

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

    @GetMapping("/")
    public String apiRoot() {
        return "This is the root of API";
    }
}

它应该会起作用。

f0brbegy

f0brbegy3#

在主类中使用@CompnentScan(基础包名称),然后试试这个,可能会奏效

相关问题