Over a million developers have joined DZone.

Creating REST Web Services With Spring Boot Hosted on Payara Micro

Learn to create a simple REST web service with Spring Boot and Payara Micro for a microservices environment.

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

Spring Boot is an application-bootstrapping framework that helps with the creation of Spring based applications with no necessary XML configuration or code generation.  It eases the configuration with its starter pom definitions and bootstrap annotations.

In a microservice ecosystem, getting a service up and running it instantly without any hassle can be difficult. In this article, we will demonstrate this approach and create a simple REST web service with Spring Boot. We’ll then host it on Payara Micro, the application server that allows you to run Java EE applications on cluster with a small footprint (~60mb) and directly from the console.

All of the examples in this article are based on Spring Boot version 1.2.6.RELEASE and Payara Micro version 4.1.153, which are the latest available versions at the time of writing. Here you can download the complete source code given in the article

Project Creation and Dependency Setup

First things first, let’s start with creating our project infrastructure. We’ll choose maven for it, since Spring Boot works well with it. You can either create a maven-ized empty web application via your favorite IDE, or you can execute the archetype command as follows. Archetypes are maven projects that also create maven-based projects.

mvn archetype:create -DgroupId=fish.payara.appserver -DartifactId=payara-micro-with-spring-boot-rest -Dversion=1.0 -DarchetypeArtifactId=maven-archetype-webapp

Next step is to add the dependencies. Spring Boot dependencies can either be integrated to a maven project through a parent pom definition or with a dependency management definition. Assuming that your project has its own maven parent project definition in its pom.xml, we added a dependency management definition for all the Spring Boot dependencies. Keep in mind that this does not add any dependencies directly to your project but allows you to select the ones you want via the<dependency> tag. And you don’t need to define <version> for each of those dependencies since it’s defined in the dependency management configuration already. The aforementioned definition is as follows:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.2.6.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Now we can add the spring-boot-starter-web module dependency, which is a starter pom 'that bootstraps you for doing web application development with Spring. With Spring Boot’s starter pom, there is no need to explicitly deal with dependencies of Spring. For starter-web, dependencies like spring-web and spring-webmvc automatically added to your project.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

One thing to be noted with the definition here: we have excluded the spring-boot-starter-tomcat transitive dependency since we will deploy our war module directly to Payara Micro, which already contains resources for Java EE. Of course the exclusion of this dependency will lead to compilation errors, so Servlet API dependency needs to be added with provided scope as given follows:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

We like to stick with the latest and greatest at all times, so in order to compile our source with Java 8, we added maven-compiler-plugin definition with 1.8 compiler arguments. Keep in mind that maven compiles source code with Java 5 level by default.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <compilerArguments>
            <source>1.8</source>
            <target>1.8</target>
        </compilerArguments>
    </configuration>
</plugin>

Project Creation and Dependency Setup

First things first, let’s start with creating our project infrastructure. We’ll choose maven for it, since Spring Boot works well with it. You can either create a maven-ized empty web application via your favorite IDE, or you can execute the archetype command as follows. Archetypes are maven projects that also create maven-based projects.

mvn archetype:create -DgroupId=fish.payara.appserver -DartifactId=payara-micro-with-spring-boot-rest -Dversion=1.0 -DarchetypeArtifactId=maven-archetype-webapp

Next step is to add the dependencies. Spring Boot dependencies can either be integrated to a maven project through a parent pom definition or with a dependency management definition. Assuming that your project has its own maven parent project definition in its pom.xml, we added a dependency management definition for all the Spring Boot dependencies. Keep in mind that this does not add any dependencies directly to your project but allows you to select the ones you want via the<dependency> tag. And you don’t need to define <version> for each of those dependencies since it’s defined in the dependency management configuration already. The aforementioned definition is as follows:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.2.6.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Now we can add the spring-boot-starter-web module dependency, which is a starter pom 'that bootstraps you for doing web application development with Spring. With Spring Boot’s starter pom, there is no need to explicitly deal with dependencies of Spring. For starter-web, dependencies like spring-web and spring-webmvc automatically added to your project.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

One thing to be noted with the definition here: we have excluded the spring-boot-starter-tomcat transitive dependency since we will deploy our war module directly to Payara Micro, which already contains resources for Java EE. Of course the exclusion of this dependency will lead to compilation errors, so Servlet API dependency needs to be added with provided scope as given follows:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

We like to stick with the latest and greatest at all times, so in order to compile our source with Java 8, we added maven-compiler-plugin definition with 1.8 compiler arguments. Keep in mind that maven compiles source code with Java 5 level by default.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <compilerArguments>
            <source>1.8</source>
            <target>1.8</target>
        </compilerArguments>
    </configuration>
</plugin>

Bootstrapping the REST Web Service

First we need to implement a main configuration class annotated with the @SpringBootApplication and it will be responsible for configuring and starting our application. @SpringBootApplication is a composing annotation provided by Spring Boot and it bundles @Configuration, @EnableAutoConfiguration and @ComponentScan annotations together in one place. The main class named Application is given below.

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

The Application class extends SpringBootServletInitializer class and overrides the configure method. This is needed since we want to deploy our application as a war archive onto Payara Micro by following the traditional approach, instead of using embedded servers of the Spring Boot.

The implementation of the REST web service is based on Spring MVC module and with the help of Spring Boot, we didn’t deal with any of its configuration like DispatcherServlet definition etc. The controller annotated with@RestController defines a person map and initializes it with 3 persons. The getAll() method just responses back with all the persons.

@RestController
@RequestMapping("/person")
public class PersonRestController {

    Map<Integer, Person> personMap = new HashMap<>();

    @PostConstruct
    public void init() {
        personMap.put(1, new Person(1, "Mert", "Caliskan", "m**@gmail.com"));
        personMap.put(2, new Person(2, "Steve", "Millidge", "s**@c2b2.co.uk"));
        personMap.put(3, new Person(3, "Andrew", "Pielage", "a**@c2b2.co.uk"));
    }

    @RequestMapping("/all")
    public Collection<Person> getAll() {
        return personMap.values();
    }
}

Wrapping it Up

The web.xml, web application deployment descriptor file, should be placed under WEB-INF folder in order to package the application as a war file first. Also the file is needed to correctly deploy our application onto Payara Micro. An empty Java EE7 compliant web.xml definition (note that it’s version 3.1, which aligns with Servlet 3.1 of Java EE7) is given below.

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
     http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

</web-app>

Executing mvn clean install command within the application folder should create a war archive out of it.

Getting it Up and Running

With Payara Micro it’s very easy to deploy a war archive through the console. Download Payara Micro 4.1.153 from herefirst, and then just execute the command given below.

java -jar payara-micro-4.1.153.jar --deploy %PATH_TO%/payara-micro-with-spring-boot-rest-1.0.war

You should be seeing an output similar to this:

Image title

By requesting for the URL http://localhost:8080/payara-micro-with-spring-boot-rest-1.0/person/all, you will be getting a JSON output as follows:

[ 
   { 
      "id":1,
      "name":"Mert",
      "lastName":"Caliskan",
      "email":"m*@gmail.com"
   },
   { 
      "id":2,
      "name":"Steve",
      "lastName":"Millidge",
      "email":"s*@c2b2.co.uk"
   },
   { 
      "id":3,
      "name":"Andrew",
      "lastName":"Pielage",
      "email":"a*@c2b2.co.uk"
   }
]

Integrating Actuator

In a microservice based ecosystem, monitoring your services and health-checking can be quite crucial. Spring Boot offers the Actuator module that helps monitoring your application through built-in endpoints.  Just add starter pom of actuator as follows and you can request for http://localhost:8080/payara-micro-with-spring-boot-rest-1.0/health to see the status of your service.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

To get the list of all endpoints, just request for http://localhost:8080/payara-micro-with-spring-boot-rest-1.0/mappings



Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
spring boot ,spring ,payara ,microservices ,rest ,java ee ,spring framework

Published at DZone with permission of Mert Caliskan. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}