[Example] A Simple Spring Boot REST Web Application

A Spring Boot application uses the @SpringBootApplication annotation over the main executable class. The SpringApplication.run method call accepts two parameters — the configuration class annotated with @SpringBootApplication annotation and any application arguments. 


Bean Components

We will use a simple bean class based on our previous examples. 

Within the bean file, we will use the annotation @RestController and @RequestMapping to expose the class as a service and to map to a url pattern. We will also change the signature of the bean's method to return a string that will be displayed in the browser.


package com.javajee.springboot;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

class JJWriter {
    public String write() {
        return "<h2>Inside JJWriter's method write()</h2>";


Test Class (Main class)

A Spring Boot application can be created using the annotation @SpringBootApplication.

We will cleanup the JJWriterMain method from the previous example and it will only have the SpringApplication.run method call.


package com.javajee.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class JJWriterMain {

    public static void main(String[] args) {
        SpringApplication.run(JJWriterMain.class, args);

Before executing the program, you must have also configured your Gradle/Maven dependencies.


Maven POM File

You need to add Spring Boot dependencies instead of Spring dependencies. Spring Boot provides easy to use starter pom dependencies such as spring-boot-starter, spring-boot-starter-test, spring-boot-start-web.

Only thing you will need to change in the pom.xml from the previous example is to change spring-boot-starter with spring-boot-start-web.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">




Executing and verifying the program

You can execute the main class and verify the program by running http://localhost:8080/ in the browser.


Changing Port With Application.properties file

If you create a file called application.properties within the resources folder, Spring Boot will automatically pick it up as the default properties file.

For example, you can change the default port of the embedded tomcat server by adding below line to the application.properties file.

server.port = 8090

Now you can execute the main class and verify the program by running http://localhost:8090/ in the browser.

This may be required in case of any port conflicts or simply as a personal choice.

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!