【问题标题】:Spring Boot , GET invocation not working in Postman [duplicate]Spring Boot,GET调用在邮递员中不起作用[重复]
【发布时间】:2022-01-16 20:03:24
【问题描述】:

这里是春季新手。三类

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

邮递员执行 GET 员工会引发此错误(404)

项目设置

【问题讨论】:

    标签: java spring-boot api rest get


    【解决方案1】:

    在 Spring Boot 应用程序中,可以定义一个属性 server.servlet.context-path,它是应用程序的根路径。

    在 application.properties 中搜索此属性,如果已定义,请将其添加到您使用 Postman 调用的 url 路径中。

    如果不是这种情况,那么您可以在具有main 方法的类中使用以下注释,该方法具有@SpringBootApplication

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

    【讨论】:

    • 按照建议尝试了@RequestMapping,但没有改变。我需要清除 Tomcat 或 Postman 中的任何机会吗?
    • @Raghu 你把它部署为战争吗?
    • 不,这只是在我的 Eclipse 环境中
    • @Raghu 检查更新的答案
    • 我的 application.properties 是一个空白文件。
    【解决方案2】:

    由于您的主要应用程序类在包演示下, 使用@SpringBootApplication,它会扫描演示包及其所有子包。 在这种情况下,您的控制器不会被扫描。 解决方案之一是重新组织您的包。 例如,删除演示包。

    【讨论】:

      【解决方案3】:

      你把这个@SpringBootApplication 放到你的主类了吗? 似乎您的控制器没有被扫描。 https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/using-boot-using-springbootapplication-annotation.html

      【讨论】:

      • 这个注解已经在主类中了
      • 您是否将控制器放在 YourSpringBootMainApplication.java 包之外的其他包中?
      猜你喜欢
      • 2019-08-25
      • 1970-01-01
      • 2021-03-05
      • 2020-08-18
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      相关资源
      最近更新 更多