Spring boot and spring data jpa tutorial - A sample application using spring 4.0 spring boot and JPA (part 1/2)

Spring boot is a strongly opinionated framework / generator based on the principle of convention over configuration, which according to the website:

Spring Boot makes it easy to create Spring-powered, production-grade applications and services with absolute minimum fuss. It takes an opinionated view of the Spring platform so that new and existing users can quickly get to the bits they need

Basically by using a few annotations and minimum boilerplate code the framework/generator will configure all the necessary beans and contexts based on a set of conventions.

Spring boot has a few modules that depending on your needs can speed-up development such as :

  • spring data jpa
  • spring data mongodb
  • spring web
  • spring actuator
  • ...

Personally I find that when using the spring stack this tool is pretty awesome!!

When using this tool you must know that there are actually 2 ways to use spring boot :

  1. Using the cli (and by extension groovy)
  2. Using good old maven and the spring-boot plugins

In this tutorial we will be building a simple Hello World tutorial as a RESTful web service

1.- Getting things started

Add the required maven dependencies to your pom.xml

        spring-boot-hello-world-ws
    spring-boot-hello-world-ws
    1.0-SNAPSHOT


    
    
        org.springframework.boot
        spring-boot-starter-parent
        1.0.0.RC1
    

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

    

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

        
    

    
    
    
        
            spring-snapshots
            http://repo.spring.io/snapshot
            
                true
            
        
        
            spring-milestones
            http://repo.spring.io/milestone
            
                true
            
        
    
    
        
            spring-snapshots
            http://repo.spring.io/snapshot
        
        
            spring-milestones
            http://repo.spring.io/milestone
        
    

So what's happening here :

  • Since spring-boot is not G.A. yet you will need to include the Spring milestones repositories
  • When using maven your project will have to inherit from the spring boot starter parent in order for it to work
  • We are using the web module (see dependencies)
  • The spring-boot-maven-plugin will build a runnable jar file

2.- Creating our first controller

With the basic configuration out of the way we can start building our app.

Since this is going to be a RESTful API we will create a REST controller. Spring included a new annotation in the latest version @RestController. Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default; which in our case it's what we want.

So with that being said let's write our first controller :


package com.ufasoli.tutorials.spring.boot.web.controllers;

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

/**
 * Created with IntelliJ IDEA.
 * User: Ulises Fasoli
 * Date: 04.02.14
 * Time: 15:33
 */
@RestController
@RequestMapping(value = "/hello", produces = MediaType.APPLICATION_JSON_VALUE)
public class HelloWorldController {

    @RequestMapping
    public String sayHello(){
        return "Hello World";
    }
}

Nothing special here just a simple Spring MVC controller but using the new @RestController annotation

We are now 2 steps away from running our Spring app.

3.- Creating our Spring Application main class

In order for the Spring context to be bootstrapped you will need to create a class that will run the Spring application inside a main method and a few annotations.So let's go ahead and do that :

package com.ufasoli.tutorials.spring.boot;

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

/**
 * Created with IntelliJ IDEA.
 * User: Ulises Fasoli
 * Date: 04.02.14
 * Time: 11:39
 *
 */
@ComponentScan // spring standard component scan
// spring boot autoconfiguration will bootstrap your Spring
//application while attempting to configure the beans you need
// it will also bootstrap an in-memory database if a driver is found
// in the classpath and no datasource is defined
@EnableAutoConfiguration
public class HelloWorldApp {

    public static void main(String[] args) throws Exception {

        SpringApplication.run(HelloWorldApp.class, args);

    }
}


What's happening here? :

  • The @Component is standard spring annotation to search for annotated beans in the classpath
  • The @EnableAutoConfiguration is spring boot specific and will be doing most of the "magic"

We are now one step away from running our spring application! Yep that's it no web.xml configuration, no XML files, nothing!!

4.- Taking it for a spin

With the application configured it's time to test our app, so fire-up your IDE or your console and execute the following maven goal :

  mvn clean package

Once your app is packaged you can run the generated runnable JAR file by simple going into the target folder and running :


  java -jar .\spring-boot-hello-world-ws-1.0-SNAPSHOT.jar
 

If everything worked as expected you should see the Spring boot / maven output in your console :


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.0.0.RC1)

2014-02-04 15:46:47.628  INFO 12516 --- [           main] c.u.tutorials.spring.b
oot.HelloWorldApp  : Starting HelloWorldApp on LTULF01 with PID 12516 (C:\dev\wo
rkspaces\idea\java-blog-tutorials\spring-boot-hello-world-ws\target\spring-boot-
hello-world-ws-1.0-SNAPSHOT.jar started by ULF)
....

That's it you can now test your controller by calling the url :

 curl http://localhost:8080/hello.json

You should see the Hello world message printed out in the console

Personally it kind of bugs me to have to package the app and then run it manually so on part 2 of this tutorial we will change this so Maven will do the work for us.....

No comments:

Post a Comment

OSX show used ports or listening applications with their PID

On OSX you can display applications listening on a given port using the lsof the commands described below will show listening application...