REST API Using Spring BootIn this guide we will see how to use Spring Boot to implement a REST API. 1. Create a Spring Boot ProjectGo to Spring Initializr and create a project with the following options:
Click the Generate button to download the project, then in Eclipse, use the Import Existing Maven Project function to import it into Eclipse. 2. Configure Database AccessUnlike the myriad of configuration files in regular Spring, everything in Spring Boot uses the same configuration file src/main/resources/application.properties, and a large part of learning Spring Boot is learning the configuration properties.I recommend that you put this file in your .gitignore so you don't accidentally check this file into your source version control -- instead of, version control a application.properties.sample file showing the configuration properties you use with sample values. To connect to a database, we'll need the following properties:
Spring Boot uses Hibernate MySQL5Dialect by default. To use MySQL8Dialect instead:
And we can use the following property to automatically create the schema in the database when the application starts:
You can check out the documentation for ways to fine control how the database is initialized. 3. REST API Example Add the following code to the project -- note that you may need to change the package names to match your project: Run the application, and it should automatically create the schema in the database configured in the previous step. You can insert some data into the products table, then go to the URL http://localhost:8080/products to see the list of products in JSON format. |