reset password

REST API Using Spring Boot

In this guide we will see how to use Spring Boot to implement a REST API.

1. Create a Spring Boot Project

Go to Spring Initializr and create a project with the following options:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: the latest stable version (currently 2.1.8)
  • Project Metadata: specify the Group Id and Artifact Id of your project. Under Options, select the Java version you prefer (I recommend 8) and make sure Packaging is Jar.
  • Dependencies: Spring Web, Spring Data JPA, and MySQL Driver (or the driver for the DBMS of your choice)

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 Access

Unlike 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.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Spring Boot uses Hibernate MySQL5Dialect by default. To use MySQL8Dialect instead:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

And we can use the following property to automatically create the schema in the database when the application starts:

spring.jpa.generate-ddl=true

You can check out the documentation for ways to fine control how the database is initialized.

This page has been viewed 4323 times.