Getting started is a commonly seen phrase in technical guides or articles. With Spring framework, getting started has never been really fast enough for a long time until Spring Boot. In this article we’ll discuss how you can actually get started really fast with Spring using Spring Boot.
Bootstrapping
How about creating a simple web application that talks to a database in Spring? How about doing this in say 5-10 minutes? Now that’s really fast. When I compare it with the earlier versions of Spring this would take me sweet half an hour. Let’s achieve this in Spring Boot. Spring Boot is an agile way of creating Spring applications without the plumbing work required to set up and configure the environment. It gives you a number of readymade features that makes a developer get the job done as quickly as possible.
Agile setup
Getting started with Spring Boot is very easy. You can use Gradle or Maven and configure the Spring Boot dependencies and plugins. There’s another option, Spring Boot CLI, which is a command-line tool that can be used to execute Spring code written in Groovy. I’m going to use Gradle in this article. Let’s setup Spring Boot using Gradle, write some code and run it.
Baby steps with Spring Boot
What’s the first thing that we would love to do in Spring? Create a class; configure it as a bean in the XML file; and load it using the container. Oh yes! this is only after you add the dependent jars to the classpath. Let’s write a component SampleClass and load it using the container. I’ve not used any IDE to implement this example.
package com.healthycode.pojo; import org.springframework.stereotype.Component; @Component public class SampleClass{ public void doSomething(){ System.out.println("I'm trying to do something useful"); } }
Let’s create a main class, create ApplicationContext and load our SampleClass bean.
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.ApplicationContext; import com.healthycode.pojo.*; @EnableAutoConfiguration @ComponentScan(basePackages = "com.healthycode") public class Main{ public static void main(String[] args){ ApplicationContext context = SpringApplication.run(Main.class,args); SampleClass sampleClassInstance = context.getBean("sampleClass",SampleClass.class); sampleClassInstance.doSomething(); } }
Hmm, did you notice the word boot in the code? The SpringApplication class creates the ApplicationContext by loading the configuration settings through the use of @EnableAutoConfiguration and @ComponentScan annotations in the Main. What about an XML file that you may need to configure the beans? ☺☺
It’s time to compile and execute the code using Spring Boot. Spring Boot gives you a number of starter libraries. Choose the starter library that you need in your application and add that as a dependency. You can find the list of all starter libraries at https://github.com/spring-projects/spring-boot/tree/master/spring-boot-starters. You will get more comfortable with Spring Boot starters as we move on. To begin with, let’s use the basic dependency, spring-boot-starter.
Let’s create build.gradle and configure the Spring Boot plugin and the spring-boot-starter dependency. You can find an initial gradle file at https://github.com/spring-guides/gs-spring-boot/blob/master/initial/build.gradle.
buildscript { repositories { mavenCentral() maven { url "http://repo.spring.io/snapshot" } maven { url "http://repo.spring.io/milestone" } } dependencies { classpath "org.springframework.boot:spring-boot-gradle-plugin:1.1.0.BUILD-SNAPSHOT" } } apply plugin: 'java' apply plugin: 'spring-boot' jar { baseName = 'HealthyCode' version = '0.0.1-SNAPSHOT' } repositories{ mavenCentral() maven { url "http://repo.spring.io/snapshot" } maven { url "http://repo.spring.io/milestone" } } dependencies { compile "org.springframework.boot:spring-boot-starter" }
Spring provides a nice UI to generate a Spring boot build configuration file at http://start.spring.io/.
Alright! Bring up your command prompt and type in gradle run and you should see the output.
Let’s toss in a DAO
We wrote a HelloWorldlish example. Let’s do some real work. We’ll create a service class, wire in a DAO and run it using Spring Boot. I have a simple database called springboothealthycode created in MySQL. It has a table called product with id,name,description and price columns. Here’s the ProductDao class that has a very simple insert method.
package com.healthycode.dao; import org.springframework.stereotype.Repository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; @Repository public class ProductDao{ @Autowired private JdbcTemplate jdbcTemplate; public boolean insert(String name,String description,double price){ int rowsUpdated = jdbcTemplate.update("insert into product(name,description,price) values(?,?,?)",name,description,price); return rowsUpdated != 0; } }
I have used JdbcTemplate in ProductDao and marked it as a Repository. The ProductService class that uses the ProductDao is shown here.
package com.healthycode.service; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; import com.healthycode.dao.ProductDao; @Service public class ProductService{ @Autowired private ProductDao productDao; public boolean addProduct(String name,String description,double price){ return productDao.insert(name,description,price); } }
In the Main class let’s create an instance of ProductService and access the addProduct() method.
ProductService productService = context.getBean("productService",ProductService.class); productService.addProduct("Moto G","Black, with 16GB",13999);
We need to add the MySQL connector jar and spring-boot-starter library for jdbc in build.gradle, to make this work.
... dependencies { compile "org.springframework.boot:spring-boot-starter" compile "org.springframework.boot:spring-boot-starter-jdbc" compile "mysql:mysql-connector-java:5.1.16" } ...
The jdbc starter takes care of loading the necessary files. Oh, wait a sec. Where do you specify the database information? Spring Boot looks for the database information in application.properties file.
spring.datasource.url=jdbc:mysql://localhost/springboothealthycode spring.datasource.username=root spring.datasource.password=password spring.datasource.driverClassName=com.mysql.jdbc.Driver
That’s it!!! It cannot get simpler than this.
How about some web interface?
Let’s build a web interface for the ProductService. We’ll create a RESTful service and add a product. The class ProductController does this.
package com.healthycode.web; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.beans.factory.annotation.Autowired; import com.healthycode.service.ProductService; @RestController @RequestMapping("/products") public class ProductController { @Autowired private ProductService productService; @RequestMapping("/add/{name}/{price}") public String add(@PathVariable String name,@PathVariable double price) { productService.addProduct(name,"",price); return "Added succesfully"; } }
In the add() method I have left out the description of the product to keep things simple. Let’s add a spring-boot-starter for web to our build file.
... dependencies { compile "org.springframework.boot:spring-boot-starter" compile "org.springframework.boot:spring-boot-starter-jdbc" compile "mysql:mysql-connector-java:5.1.16" compile "org.springframework.boot:spring-boot-starter-web" }
Run build.gradle. The web module is loaded with an embedded tomcat running in port 8080. That’s real quick! Enter http://localhost:8080/products/add/MotoG/139999 in your browser to see the output.
Final thoughts
If you have the neccessary tools like Gradle or Maven already installed, this example wouldn’t have taken more than 10 minutes. So in 10 minutes of time, you have created a simple RESTful web application that talks to database and stores values using Spring. And this is made possible in such a short span, thanks to Spring-Boot. You can extend it further test the code, customize the environment, include other Spring modules like AOP, Messaging and all of these in an agile manner using Spring Boot.
You can find the complete code for the article in https://github.com/healthycodemagazine/june2014.
You can download the complete article as a PDF document from http://healthycodemagazine.com/articles#bootstrap_with_spring_boot_prabhu