Hello World REST Service with Spring boot

Recently I tried creating RESTful service with Spring Boot.  Its very easy to create RESTful service using Spring Boot, and also it removes lots of boilerplate code.

I will be walking through creating a simple hello world service. I have used Intellij Idea 15 and Java SDK 1.8, Maven 4.0.0 to build and run the project.

Lets start by creating a maven based project in Intellij. Specified required  SDK, groupId, artifactId and project name.

Now create a directory named "hello" under src->main->java.  Create a new Java class named HelloController (under directory 'hello'). Add below code to HelloController.Java

package hello;

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

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String sayHello() {
        return "Hello World with Spring Boot !!!";
    }
}
Your hello REST controller is ready now.
Create Application.Java file under src->main->java->hello directory. Update Application.java with below code.

package hello;

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

@SpringBootApplication
public class Application {

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

locate your pom.xml it should be under parent directory of project.
Update pom.xml with below dependencies.

    
        1.8
    

    
        org.springframework.boot
        spring-boot-starter-parent
        1.3.3.RELEASE
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

Now to run the application, create application run configuration. Select project and click on edit configuration (Under Run menu). Add new configuration for "Application", for Main class select hello.Application. Set the working directory as project root and OK.

Now run the application and go to your browser and hit "http://localhost:8080/hello"

You should see the service returns with "Hello World with Spring Boot!!!".

Reference : Rest-service with Spring

No comments:

Post a Comment

Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...