简体   繁体   English

无法通过 url 访问我的 spring 启动应用程序

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

I try to access my endpoint with local host url - http://localhost:8080/all this is my Application.java file我尝试使用本地主机 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);
    }

}

and this is my end point这是我的终点

@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();
    }
}

and I try with this url - http://localhost:8080/all我尝试使用这个 url - http://localhost:8080/all

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

This kind of problem might happen due to some components(like controller, service, etc) not being scanned by spring due to components and the Main class being in a different package. Here, Your main class is in com.example.MyApplication package. So If you keep all other components(like controller, service, etc) of the spring boot in the same package or sub-package then that will work as expected.这种问题可能由于某些组件(例如controller,服务等)而发生,而不是由spring扫描,这是由于组件和主要的class在不同的package.RES com.example.MyApplication package888888888888888888888888888881215121.因此,如果您将 spring 引导的所有其他组件(如 controller、服务等)保留在同一个 package 或子包中,那么它将按预期工作。 If you want to keep those in the different packages you need to mention those different packages which are having spring components like controllers in the @ComponentScan annotation.如果您想将它们保留在不同的包中,您需要在@ComponentScan注释中提及那些具有 spring 组件(如控制器)的不同包。

Change GetAll class's package declaration if you can keep them in the same package:如果可以将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();
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM