簡體   English   中英

Spring 啟動,GET 調用在 Postman 中不起作用

[英]Spring Boot , GET invocation not working in Postman

Spring 新手在這里。 三班

員工.java

package com.example.model;

public class Employee {

private int employeeId;
private String name;
private String email; 

public Employee(int employeeId, String name, String email)
{
    this.setEmployeeId(employeeId);
    this.setName(name);
    this.setEmail(email); 
}

public int getEmployeeId() {
    return employeeId;
}

public void setEmployeeId(int employeeId) {
    this.employeeId = employeeId;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

EmployeeDao.java

@Component
public class EmployeeDao {

static List<Employee> list = new ArrayList<>();
        
        static 
        {
            list.add(new Employee(1234,"Nancy", "nancy@mail.com"));
            list.add(new Employee(5678, "Daniel","daniel@mail.com"));
            list.add(new Employee(9101, "Scott", "scott@mail.com"));
        }

public List<Employee> getAllEmployees()
 {
    return list;
 }

}

EmployeeController.java

@RestController
public class EmployeeController {

@Autowired
EmployeeDao service;

@GetMapping(path = "/employees")    
public List<Employee> getAll()
 {
    System.out.println(service.getAllEmployees());
    return service.getAllEmployees();
 }
}

Postman 執行 GET 員工引發此錯誤 (404) 在此處輸入圖像描述

項目設置

在此處輸入圖像描述

在 spring 引導應用程序中,可以定義一個屬性server.servlet.context-path ,它是應用程序的根路徑。

在 application.properties 中搜索此屬性,如果已定義,請將其添加到您使用 Postman 調用的 url 路徑中。

如果不是這種情況,那么您可以在 class 中使用以下注釋,該注釋具有具有@SpringBootApplicationmain方法

@ComponentScan({"com.example.service", "com.example.model"})

由於您的主要應用程序 class 在 package 演示下,它使用 @SpringBootApplication 掃描演示 package 及其所有子包。 在這種情況下,不會掃描您的 controller。 解決方案之一是重新組織您的包。 例如,刪除演示 package。

你把這個@SpringBootApplication 放到你的主 class 了嗎? 似乎您的 controller 未被掃描。 https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/using-boot-using-springbootapplication-annotation.ZFC35FDC70D5FC69D2539883A822EZ7

暫無
暫無

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

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