Spring Boot跨类访问实例变量及Postman请求体示例
Hey there! Let's work through your two requirements one by one, and first fix a small syntax issue in your Material class definition to avoid compilation errors.
First: Fix the Map Declaration in Material Class
I noticed a typo in your Map definition: Map<warehouseCode, Quantity> warehouse; won't work because warehouseCode isn't a valid Java type. Since the warehouseCode from your Warehouse class is a String, update the line to:
private Map<String, Quantity> warehouse;
This correctly maps each warehouse code (String value) to its corresponding Quantity.
1. Accessing WarehouseCode from Material's Map
With the Map properly defined, you can access warehouse codes (they're the keys of the Map) in your service or controller logic. Here's a practical example of how to iterate through all warehouse codes and their associated stock quantities:
Example in MaterialService
public void processMaterialWarehouseData(Material material) { // Fetch all warehouse codes from the Map's key set Set<String> warehouseCodes = material.getWarehouse().keySet(); for (String code : warehouseCodes) { Quantity stockQuantity = material.getWarehouse().get(code); // Perform your desired operations with the warehouse code and quantity System.out.printf("Warehouse Code: %s | Available Stock: %d%n", code, stockQuantity.getQuantity()); } }
If you need to target a specific warehouse code directly, use material.getWarehouse().get("WH001") (replace "WH001" with your target code).
2. Postman POST Request Body Example
Below is a complete JSON request body you can use in Postman for your /material endpoint. It aligns with your Material class structure and includes the warehouse Map with multiple warehouse entries:
{ "materialId": "MAT-0001", "materialGroup": "Electronics", "materialCode": "LAPTOP-PRO", "materialType": "Consumer Goods", "materialDimension": "35x25x2cm", "materialDescription": "15-inch Pro Laptop with 16GB RAM", "status": "ACTIVE", "materials": [], // Leave empty if no child materials, or remove the field entirely "warehouse": { "WH-NY-001": { "quantity": 120 }, "WH-LA-002": { "quantity": 85 }, "WH-TX-003": { "quantity": 50 } } }
Quick Notes for the Request Body:
creationDateandupdateDate: These fields are initialized withLocalDate.now()in your class, so you don't need to include them in the request—your backend will auto-set their values.materialsList: If you don't need to include child Material instances, you can either leave it as an empty array or omit the field from the JSON entirely.- Warehouse Entries: Add/remove key-value pairs in the
warehouseobject as needed, where each key is your warehouse code (string) and the value is aQuantityobject with thequantityfield.
内容的提问来源于stack exchange,提问作者briancoder

