在 Spring Boot 中创建一个包含名称、价格和数量的水果表的步骤如下:

  1. 创建一个名为 Fruit 的 Java 类,用于表示水果表的实体。在该类中定义名称、价格和数量的属性,并提供相应的 getter 和 setter 方法。
public class Fruit {
    private String name;
    private double price;
    private int quantity;

    public Fruit() {
    }

    public Fruit(String name, double price, int quantity) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    // getter 和 setter 方法

    public String getName() {
        return name;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
}
  1. 在 Spring Boot 应用的主类中创建一个名为 FruitController 的 REST 控制器,用于处理水果表的相关请求。
@RestController
@RequestMapping("/fruits")
public class FruitController {
    private List<Fruit> fruits = new ArrayList<>();

    @GetMapping
    public List<Fruit> getAllFruits() {
        return fruits;
    }

    @PostMapping
    public void addFruit(@RequestBody Fruit fruit) {
        fruits.add(fruit);
    }
}
  1. 运行 Spring Boot 应用,并通过 HTTP 请求访问水果表的相关接口,例如:
  • 获取所有水果的接口:GET /fruits
  • 添加水果的接口:POST /fruits,请求体为包含名称、价格和数量的 JSON 对象

这样就可以通过 Spring Boot 创建一个包含名称、价格和数量的水果表。

Spring Boot 创建水果表:名称、价格、数量

原文地址: https://www.cveoy.top/t/topic/qEYO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录