| .mvn/wrapper | ||
| src | ||
| .gitattributes | ||
| .gitignore | ||
| mvnw | ||
| mvnw.cmd | ||
| pom.xml | ||
| Readme.md | ||
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