Prabhu Sunderaraman

Fullstack Engineer, Programmer, Writer, Trainer

prabhu.bits@gmail.com,     GitHub     Youtube     LinkedIn
  • Home
  • Profile
  • Books
  • Reading List
Browsing: / Home
Shortlink

Bootstrap with Spring Boot

By Prabhu Sunderaraman on July 29, 2014 in Spring

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

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

A Concurrency activity using Scala and Akka – II

By Prabhu Sunderaraman on July 1, 2014 in Scala

In the previous post I discussed the problem of connecting to AWS instances concurrently and how slow it was when we implement it sequentially. We need to connect to hundreds of MySQL instances, fetch some records and store them in files. The records contained different URLs that needs to be accessed. I will just discuss the first part of accessing the records in MySQL and storing them in files.

Scala gives you the Actor model to implement concurrency. You create multiple actors and make them interact with each other by passing messages. Each actor instance can be looked upon as a thread that has some local data and behavior. You invoke the actor by passing messages. The messages are queued and executed one by one by the actor instance. So you can create hundreds of actor instances each doing a chunk of work. So if you have to connect to hundreds of database instances you define an Actor for connecting to the instance and executing the query and an actor for storing the records in separate files.

I used the Akka library to implement this. I used a RoundRobinRouter to create some 100 instances of the actors that will be used in a round robin fashion. In fact I used two Actors for storage purpose become of an intrinsic complexity involved, which is beyond the scope of this topic.

A sample code that connects to MySQL is shown here.

class DBActor(storageActor1:ActorRef,
                  storageActor2:ActorRef) 
  extends Actor{ 
  
  def accessTable1(stmt:Statement):(String,String) = {
      //EXECUTE QUERY
  }
  
  def accessTable2(stmt:Statement):(String,String) = {
      //EXECUTE QUERY
  }
  
  def receive = {
      case credentials:DBCredentials => {
	 try{
		val url = "jdbc:mysql://" + credentials.endpoint + "/aws"
		val con = //create connection
		val stmt = con.createStatement()
		val data1 = accessTable1(stmt)
		val data2 = accessTable2(stmt)
		storageActor1 ! data1
		storageActor2 ! data2
	}
	catch{
		case ex:Exception => {
			val dbErrorLevel1:DBErrorLevel1 = new DBErrorLevel1(credentials.fileName,ex.getMessage)
			storageActor1 ! dbErrorLevel1

		}
	}

     }
  }
}

An important aspect of the Actor model is you don’t have to worry about the synchronization nemesis in the Threading API. The DBActor connects to the MySQL instance and stores the records in different files using two other actors who do that job. And you can start the system using the RoundRobinRouter like this.

object MyApplication extends App{
   val inputFolder = "./src/main/resources/Files"
   val system = ActorSystem("MyApplication")
   def getInfo(file:File):DBCredentials= {
	val lines = Source.fromFile(file).getLines.toList
	val credentials = new DBCredentials(file.getName,lines(0),lines(1),lines(2))
	credentials
   }
   val storageActor1 = system.actorOf(Props[StorageActor1].withRouter(RoundRobinRouter(60)),name="StorageActors1")
   val storageActor1 = system.actorOf(Props[StorageActor2].withRouter(RoundRobinRouter(60)),name="StorageActors2")
   val router = system.actorOf(Props(new DBActor(storageActor1,storageActor2)).withRouter(
                        RoundRobinRouter(60)
                     ), name = "MyApplicationRouter")
    for(file <- new File(inputFolder).listFiles) {
		router ! file
    }
}

So I create almost 60 actor instances using RoundRobinRouter and start the system. We then iterate through the files that contain the database endpoint information and pass each endpoint as a message to an actor instance. Needless to say I used SBT to build this application.

//build.sbt
name := "MyApplication"

version := "1.0"

scalaVersion := "2.10.3"

mainClass in Compile := Some("MyApplication")

resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"

libraryDependencies += "com.typesafe.akka" % "akka-actor_2.10" % "2.2-M1"

libraryDependencies += "com.typesafe.akka" % "akka-actor" % "2.0"
 
libraryDependencies += "com.typesafe.akka" % "akka-remote" % "2.0"

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

A Concurrency activity using Scala and Akka – I

By Prabhu Sunderaraman on June 17, 2014 in Scala

Last month, as a part of an assignment, I had to connect to MySQL databases on Amazon Cloud and execute a couple of queries. These queries returned some URLs. I had to connect to these URLs and extract the data and store them in text files. Finally the data in these files had to be collated and mailed to a group of guys.

The crux of this job was I had to connect to around 550 odd MySQL instances on Amazon. Each instance returned three URLs. So I had to send requests to 550*3=1650 URLs. So a total of 1650+550=2220 connections. So you can visualize the magnitude of this.

Screen Shot 2014-06-17 at 11.11.18 PM

When I received the 550 endpoints to MySQL instances with their credentials I was at the Bangalore airport waiting to board the flight to Chennai. My flight got delayed by an hour, so decided to make use of the free WIFI at the airport and write a simple Groovy script. I had already planned to write a Scala program with Akka library, but based on my previous disastrous experiences of writing concurrent code on the move, thought it was safer to go home and do that.

Wrote my Groovy script that would read all the MySQL endpoints sequentially(!!!!!) and send out requests to the three URLs. It took me 20 minutes to write the Groovy script without much of error handling. I executed the code. My program started connecting to each MySQL endpoint, executed the queries and fetched the URLs; connected to those URLs and printed the output on the console. It was working beautifully as expected. The only issue was while the code was connecting to the 10th MySQL instance, the boarding announcement was on. :(

So peacefully shutdown my machine, took the flight, reached home and finished the activity using Scala and Akka. Akka is a fantastic concurrent API. It’s high level abstraction to the threads devoid of the frustrating synchronization issues that one would face while working with threads. In my next post, I will discuss the design and code to implement this problem using Scala and Akka.

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Need for Spring Boot

By Prabhu Sunderaraman on May 26, 2014 in HealthyCodeMagazine, Spring

Here’s an extract from my article on Spring Boot, in the June issue of Healthy Code magazine.

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 a 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.
Getting started with Spring Boot is very easy…

You can subscribe to the magazine here.

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

In conversation with Scott Davis

By Prabhu Sunderaraman on May 20, 2014 in HealthyCodeMagazine, JavaScript

Healthy Code interviewed Scott Davis during his recent visit to India. Here’re some of the highlights of the interview.

No one wants to go back to the days of “This web site is best viewed in Internet Explorer.”

Developing web pages that can work fine across 4″ to 15″ screens, 30″ screens, and even 60″ smart TVs hanging on a wall is a challenging one.

In the current renaissance in JavaScript, you can run it the browser, in the server tier and in the persistence tier.

Scott

You can read the complete interview in the June 2014 issue of Healthy Code Magazine.
Find out the upcoming articles.

Share this on: Mixx Delicious Digg Facebook Twitter
« Previous 1 … 28 29 30 … 64 Next »

Youtube Channel




Categories

  • JavaScript (48)
    • RequireJS (5)
  • Go (44)
  • Golang (44)
  • Ext JS (23)
  • Spring (22)
  • Mobile (21)
  • Scala (20)
    • Play (3)
  • Uncategorized (19)
  • Video Sessions (18)
  • GoG (17)
  • Sencha Touch (16)
  • jQuery (14)
  • Languages (13)
  • Java 8 (12)
  • React JS (11)
  • Kotlin (11)
  • HealthyCodeMagazine (9)
  • Video (9)
  • Objective-C (8)
  • NoSQL (8)
  • Android (7)
  • MongoDB (7)
  • GWT (6)
  • Tools (6)
  • HTML 5 (5)
  • Cloud (5)
  • General (5)
  • Micro services (5)
  • Java (5)
  • Books (4)
  • AWS (4)
  • Software Architecture (4)
  • .NET (3)
  • Elixir (3)
  • Docker (3)
  • Reactive (3)
  • NodeJS (2)
  • RoR (2)
  • Backbone (1)
  • AngularJS (1)

Archives

  • 2020 (49)
  • 2019 (7)
  • 2018 (34)
  • 2017 (15)
  • 2016 (7)
  • 2015 (18)
  • 2014 (31)
  • 2013 (55)
  • 2012 (100)

Search

Subscribe




Copyright © 2025 Prabhu Sunderaraman.

Powered by WordPress and News.