By kswaughs | Wednesday, February 24, 2016

Rest Service with Spring Boot

What is Spring Boot ?

  • Spring Boot simplifies the process of configuring and deploying the spring based applications.
  • Spring Boot is not a framework. It helps us to build, package and deploy Spring applications with minimal or no configurations.
  • Web applications or web services including RESTful services can be built as JAR file that can be run as stand-alone java application and no need to deploy in any external application server.

Spring Boot - Rest Service Example

In this below example, I will show you how to create a RESTful service with Spring Boot.

Step 1 : Use below maven dependency in your pom.xml. This jar will internally pulls all the required dependent jars in your classpath.

pom.xml
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>1.3.0.RELEASE</version>
    </dependency>
</dependencies>

Step 2 : Create a main class which will initialize and runs the spring boot application.

BootApp
package com.kswaughs.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({ "com.kswaughs.web" })
public class BootApp {
 
    public static void main(String[] args) {
  
        SpringApplication.run(new Object[] { BootApp.class }, args);

    }

}

Step 3 : Create Controller class to serve the rest service requests

UserController
package com.kswaughs.web.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.kswaughs.web.beans.UserReq;
import com.kswaughs.web.beans.UserResp;

@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    public UserResp getUser(@PathVariable String id) {

        UserResp resp = new UserResp();
  
        resp.setId(id);
        resp.setStatus("SUCCESS");
        resp.setMessage("GET Method Processed successfully");

        return resp;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public UserResp addUser(@RequestBody UserReq req) {

        UserResp resp = new UserResp();
  
        resp.setId(req.getId());
        resp.setStatus("SUCCESS");

        StringBuilder msg = new StringBuilder()
            .append("Hi ")
            .append(req.getName())
            .append(", POST method Processed successfully");
  
        resp.setMessage(msg.toString());
  
        return resp;
    }

}

Step 4 : Create below model objects to convert JSON requests and responses into java objects.

Request Object - UserReq
package com.kswaughs.web.beans;

public class UserReq {
 
    private String id;
 
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("UserReq [id=");
        builder.append(id);
        builder.append(", name=");
        builder.append(name);
        builder.append("]");
        return builder.toString();
    }
}

Response Object - UserResp
package com.kswaughs.web.beans;

public class UserResp {
 
    private String status;
 
    private String id;
 
    private String message;

    public String getStatus() {
         return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("UserResp [status=");
        builder.append(status);
        builder.append(", id=");
        builder.append(id);
        builder.append(", message=");
        builder.append(message);
        builder.append("]");
        return builder.toString();
    }
}

Step 5 : Start the application. You can start this application as a normal stand-alone java application and I am explaining below different ways of running this application.

  1. Run from Eclipse
  2. Run from Maven command
  3. Run from jar

1. Run from Eclipse

From Eclipse IDE, Go to BootApp.java class and Run as Java application.

2. Run from Maven command

Add below artifact as your parent pom in your pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.0.RELEASE</version>
</parent>

Run with maven command mvn spring-boot:run.

3. Run from jar

Add below maven build plugin

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Run maven command mvn package and it generates jar file with project_name in target directory.

Run the command java -jar target/project_name-1.0.jar from command line.

Step 6: Test the application

  
 Test 1 : 
 operation : get
 method : GET
 URL : http://localhost:8080/user/get/12345
 Response :
 
 {
    "status": "SUCCESS",
    "id": "12345",
    "message": "GET Method Processed successfully"
 }
 Test 2 :
 operation : add
 method : POST
 URL : http://localhost:8080/user/add
 Request
 { "id" : "2222", "name" : "kswaughs" }

 Response
 {
    "status": "SUCCESS",
    "id": "2222",
    "message": "Hi kswaughs, POST method Processed successfully"
 }

Recommend this on


No comments:

Post a Comment