Friday, May 8, 2020

Example of a SpringBoot data service

This is a simple database application using SpringBoot and PostgreSQL. The source code is at https://github.com/jonliu6/KnowledgeBase
  1. create a Maven project template using "mvn archetype:generate".
  2. fill in the application information.
    • groupId, artifactId, version, package
  3. open Maven project file - pom.xml and add SpringBoot and PostgreSQL dependencies.
  4. create application.properties in src/main/resources with the application name, port and database connection information.
  5. set up database and table(s) in PostgreSQL - scripts.
  6. create SpringBoot entry application class (with @SpringBootApplication)
  7. create a data model entity class (e.g. Article.java) mapping to the corresponding table (e.g. t_article).
  8. create a repository interface extends from CrudRepository from Spring Data with the common method declarations (e.g. findAll(), save() and etc.).
  9. create a controller class with org.springframework.web.bind.annotation.RestController.
    • autowire the repository in the controller.
    • create the HTTP RESTful methods in the controller.
  10. build and run the SpringBoot application by running "mvn spring-boot:run"
  11. test the controller method (e.g. http://<server>:<port>/<path>).
    • curl -X GET http://localhost:8080/articles/
    • curl -X GET http://localhost:8080/articles/Test
    • curl -X POST -H "Content-Type: application/json" -d "{"""title""":"""2nd Article for testing purpose""","""category""":"""Test""","""description""":"""This is a test record added from SpringBoot RestController again."""}" http://localhost:8080/articles/add
    • curl -X DELETE http://localhost:8080/articles/10008

No comments:

Post a Comment