簡體   English   中英

無法通過 url 訪問我的 spring 啟動應用程序

[英]Can not access my spring boot application by url

我嘗試使用本地主機 url 訪問我的端點 - http://localhost:8080/all 這是我的 Application.java 文件

package com.example.MyApplication;

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

@SpringBootApplication
public class MyApplication {

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

}

這是我的終點

@RestController("GetAll")
@RequestMapping("/all")
public class GetAll {
    private final DataService dataService;

    @Autowired
    public GetAll (DataService dataService) {
        this.dataService = dataService;
    }

    @GetMapping
    public List<DataDto> getAll() {
        return dataService.getAll();
    }
}

我嘗試使用這個 url - http://localhost:8080/all

{
    "timestamp": "2022-10-06T15:27:18.574+00:00",
    "status": 404,
    "error": "Not Found",
    "path": "/all"
}

這種問題可能由於某些組件(例如controller,服務等)而發生,而不是由spring掃描,這是由於組件和主要的class在不同的package.RES com.example.MyApplication package888888888888888888888888888881215121.因此,如果您將 spring 引導的所有其他組件(如 controller、服務等)保留在同一個 package 或子包中,那么它將按預期工作。 如果您想將它們保留在不同的包中,您需要在@ComponentScan注釋中提及那些具有 spring 組件(如控制器)的不同包。

如果可以將GetAll類的 package 聲明保留在同一個 package 中,請更改它們:

package com.example.MyApplication;

@RestController("GetAll")
@RequestMapping("/all")
public class GetAll {
    private final DataService dataService;

    @Autowired
    public GetAll (DataService dataService) {
        this.dataService = dataService;
    }

    @GetMapping
    public List<DataDto> getAll() {
        return dataService.getAll();
    }
}

參考: https://www.baeldung.com/spring-component-scanning

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM