Saturday, 24 January 2015

Spring boot : boot unnecessary things off your application development

Being Java developers, I bet most of us would have worked on JEE applications, and we all know the pain that one has to go through while setting up any JEE application. This is the point which we will discuss in this blog. We will discuss a Framework which has made enterprise applications (especially the ones having RESTful services) development radically easy. The framework in question here is Spring boot.

To understand more about how Spring boot makes RESTful web application development easy, let us point down the (approx) steps one has to go through in order to create and run an application.

Steps to create and run an enterprise Java application (w/o spring boot):
  • Install an application server.
  • Create a connection pool in the server, configure the connections.
  • Create a new application in IDE.
  • Configure deployment descriptor (i.e. web.xml, struts.xml depending upon the framework), configure mappings for different urls.
  • Create the controller classes, write the business logic to handle incoming requests.
  • Write the class to utilize the connection pool configured in server.
  • Create an archive file of the application.
  • Start the server, deploy the application archive file and then send the requests.
Now, let’s have a look at the steps involved in developing an application with Spring boot:
  • Create a new application in IDE.
  • Create the controller classes, write the business logic to handle incoming requests.
  • Run the application and send the requests.
See? This is the whole purpose of Spring boot. It takes away all the responsibilities and lets us focus on the business logic. Doesn’t it sound exciting? Let us explore more into this.

Spring data comes with inbuilt server and it lets us write our application with a simple Java class (with main method). When we run that java class, the built in server starts, connects to the database (specified in properties file, more on this later) and voila! Our application is now up and running. If you want to create an archive file, build it using any of the build tools. Build will result in a single jar file, containing all the dependencies. When you want to start the application, just run java –jar and there you go!

Let us now go through a step by step process to develop a simple spring boot application with one REST controller. We will use maven as a build tool here.
  1. Create a simple maven project in IDE, add the following in pom.xml.
    <parent>
          
    <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
                    <version>1.2.1.RELEASE</version>
    </parent>

    This helps spring identify that the application is a spring boot application. Also, add the following dependency in the same file, this will help us write the required annotations (more on this soon) as well as in building the application.

    <
    dependency>
          
    <groupId>org.springframework.boot</groupId>
          
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  2. Write a class which contains main method. The class used to start the application. An example of such class is shown below:

    @Configuration
    @EnableAutoConfiguration
    @EnableWebMvc
    @ComponentScan(basePackages = {"com.mehta"})
    public class Application {

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

    These annotations help spring identify components, controllers and database repositories in our application. These also save us from writing that cumbersome deployment descriptor. All these annotation classes are present in the dependencies we added in step 1.
  3. Write a controller class which defines the request path, type and response. Example is shown below:

    @RestController
    public class SampleController {
               
    @RequestMapping(value = "/post", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
          public Map<String, String> post(Map<String, String> body){
    Map<String, String> result = new HashMap<String, String>();
                result.put("SUCCESS", " POST Request executed                     successfully..");
                return result;
          }    
         
    @RequestMapping(value = "/get", method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
          public Map<String, String> get(){
    Map<String, String> result = new HashMap<String, String>();
    result.put("SUCCESS", " GET Request executed successfully..");
                return result;
          }
    }

    We have defined 2 methods here for POST and GET requests respectively. As we can see, the annotations defined above the methods help us defining the content type, http method type, url pattern etc (we can combine the contents of step 2 and 3 into a single class, however, for better design, I have kept them separate). The annotations are self explanatory. See how easy it is to write like this rather than stuffing everything in rather complex looking deployment descriptor xml.
  4. Add application.properties file into the project. This holds configuration information (like port number, context root, application name, database connection properties etc). For our application, add the below lines in the properties file:

    spring.application.name=
    sample
     server.port=8888management.port=8889
    server.contextPath=/sample
Et Voila! We have just created a web application using spring boot! Run the application java file, the application will start and logs will be there in console. Once application starts up, send GET/POST requests (to urls http://localhost:8888/sample/get and http://localhost:8888/sample/post respectively) and see the results. It feels awesome to develop an application like this (rather than going by that traditional way), doesn’t it? This is the whole purpose (not to let us feel awesome but to make us focus more on actual development) of Spring coming up with boot. This is what Spring website says about Spring boot:
“It takes an opinionated view of the Spring platform so that new and existing users can quickly get to the bits they need”
Spring boot also provides features to monitor the application health (when the application is deployed to production). More on this is described here.This was about simple application, what if we want to add database support into it? What if we want our application to perform CRUD operations when requests are received? Well, this is damn easy. We have to define some db properties into our application properties file and then connections to databases will be created based on those configurations. 

An example of spring boot application with Postgres is provided here (please note that we don’t need build.gradle if we are using maven) whereas an example of spring boot application with mongodb is provided here (we don’t need YAML parser or yml file for mongo configurations as we can directly use our application properties file to define the same e.g. spring.data.mongodb.host, spring.data.mongodb.port, spring.data.mongodb.url etc).

This is it then. I have uploaded the sample (that we have discussed) here. Download it and it should run straight away. Javadoc comments should provide enough information about how to execute the methods. Let me know how you get on. Comment/write to me if you face any difficulty or want more information.For once, I really think we should give spring boot framework a go. It is about time we should ditch the old school way to develop application and give this a try.

~ Cheerio