springjavademo/Readme.md
2025-09-10 06:50:08 +08:00

33 lines
1.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## Java Implementation
#### 运行方式
用./mvnw spring-boot:run运行
h2 database在 localhost:8080/h2-console
#### cURL测试
用cURL测试/api/v1/product/create
curl -X POST -H "Content-Type: application/json" --data '{"name":"product1","price":"1.0","stock":"5"}' http://localhost:8080/api/v1/product/create
返回
{"code":201,"name":"product1","message":"Product created"}
再次用cURL测试/api/v1/product/create使用相同的name
返回
{"code":409,"message":"Product with the same name already exists"}
用cURL测试/api/v1/product/{id}
curl -X GET -H "Content-Type: application/json" http://localhost:8080/api/v1/product/product1
返回
{"product":{"price":1.0,"name":"product1","stock":5},"code":200,"message":"Product retrieved"}
用cURL测试/api/v1/product/{id}使用不存在的name
返回
{"code":404,"message":"Product not found"}
#### 代码结构
- controller: 接受请求parameters然后调用service
- service: 调用repository处理业务逻辑。在必要时throw exception
- repository: 继承JpaRepository和database交互存储数据
- product: Model class
controller不直接调用repository,而是调用service负责业务逻辑。将来如要更改实现方式只需更改service和repository不用更改controller