Category Archives: Spring

Step by Step Guide to create a sample CRUD Java application using MongoDB and Spring Data for MongoDB.

MongoDB is a scalable, high-performance, open source NoSQL database. Instead of storing data in tables as is done in a “classical” relational database, it stores structured data as JSON-like documents with dynamic schemas. This post contains steps to create a sample application using MongoDB and Spring Data for MongoDB.

Spring Data for MongoDB

‘Spring data for MongoDB’ is providing a familiar Spring-based programming model for NoSQL data stores. It provides many features to the Java developers and make their life more simpler while working with MongoDB. MongoTemplate helper class support increases productivity performing common Mongo operations. Includes integrated object mapping between documents and POJOs.  As usual it translates exception into Spring’s portable Data Access Exception hierarchy.  The Java based Query, Criteria, and Update DSLs  are very useful to code all in Java. It also provides a cross-store persistence – support for JPA Entities with fields transparently persisted/retrieved using MongoDB.

You can download it from here: Download

Installing Mongo DB in just 5 steps!

There is no other place on internet which explains more clearly than its official installation reference. Following are the steps which I followed when I did its installation.

1. Download the latest production release of MongoDB from the MongoDB downloads page.

2. Unzip it into any of your convenient location say like


3. MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is C:\data\db. But we can create any folder location for storing data. I want to make it in the same MongoDB folder. So I have created a folder at the below path.


4. That’s it! Go to C:\mongodb\bin folder and run mongod.exe with the data path

C:\mongodb\bin\mongod.exe –dbpath C:\mongodb\data\db

If your path includes spaces, enclose the entire path in double quotations, for example:

C:\mongodb\bin\mongod.exe –dbpath “C:\mongodb\data\db storage place”


5. To start MongoDB, go to its bin folder and run mongo.exe. This mongo shell will connect to the database running on the localhost interface and port 27017 by default. If you want to run MongoDB as a windows service then please see it here.



Okay, this part is done. Let it run there. Now we can create a small Java application with Spring Data.

Creating an application with Spring Data (Another 5 more steps!)

We need below Jars for creating this sample project. As I am a nature lover and a GoGreen person I named the project as “NatureStore”! Using this we are going to “Save” some “Trees” in to the DB!

Step1: Create a simple domain object.

The @Document annotation identifies a domain object that is going to be persisted to MongoDB.  And the  @Id annotation identifies its id.

package com.orangeslate.naturestore.domain;


public class Tree {

	private String id;

	private String name;

	private String category;

	private int age;

	public Tree(String id, String name, int age) { = id; = name;
		this.age = age;

	public String getId() {
		return id;

	public void setId(String id) { = id;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public String getCategory() {
		return category;

	public void setCategory(String category) {
		this.category = category;

	public int getAge() {
		return age;

	public void setAge(int age) {
		this.age = age;

	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age
				+ ", category=" + category + "]";

Step2: Create a simple Interface.

Created a simple interface with CRUD methods. I have also includes createColletions and dropCollections into this same interface.

package com.orangeslate.naturestore.repository;

import java.util.List;

import com.mongodb.WriteResult;

public interface Repository<T> {

	public List<T> getAllObjects();

	public void saveObject(T object);

	public T getObject(String id);

	public WriteResult updateObject(String id, String name);

	public void deleteObject(String id);

	public void createCollection();

	public void dropCollection();

Step 3: Create an implementation class specifically for Tree domain object. It also initializes the MongoDB Collections.

package com.orangeslate.naturestore.repository;

import java.util.List;


import com.mongodb.WriteResult;
import com.orangeslate.naturestore.domain.Tree;

public class NatureRepositoryImpl implements Repository<Tree> {

	MongoTemplate mongoTemplate;

	public void setMongoTemplate(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;

	 * Get all trees.
	public List<Tree> getAllObjects() {
		return mongoTemplate.findAll(Tree.class);

	 * Saves a {@link Tree}.
	public void saveObject(Tree tree) {

	 * Gets a {@link Tree} for a particular id.
	public Tree getObject(String id) {
		return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)),

	 * Updates a {@link Tree} name for a particular id.
	public WriteResult updateObject(String id, String name) {
		return mongoTemplate.updateFirst(
				new Query(Criteria.where("id").is(id)),
				Update.update("name", name), Tree.class);

	 * Delete a {@link Tree} for a particular id.
	public void deleteObject(String id) {
				.remove(new Query(Criteria.where("id").is(id)), Tree.class);

	 * Create a {@link Tree} collection if the collection does not already
	 * exists
	public void createCollection() {
		if (!mongoTemplate.collectionExists(Tree.class)) {

	 * Drops the {@link Tree} collection if the collection does already exists
	public void dropCollection() {
		if (mongoTemplate.collectionExists(Tree.class)) {

Step 4: Creating Spring context.

Declare all the spring beans and mongodb objects in Spring context file. Lets call it as applicationContext.xml. Note we are creating not created a database with name “nature” yet. MongoDB will create it once we saves our first data.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
	xmlns:xsi="" xmlns:context=""

	<bean id="natureRepository"
		<property name="mongoTemplate" ref="mongoTemplate" />

	<bean id="mongoTemplate" class="">
		<constructor-arg name="mongo" ref="mongo" />
		<constructor-arg name="databaseName" value="nature" />

	<!-- Factory bean that creates the Mongo instance -->
	<bean id="mongo" class="">
		<property name="host" value="localhost" />
		<property name="port" value="27017" />

	<!-- Activate annotation configured components -->
	<context:annotation-config />

	<!-- Scan components for annotations within the configured package -->
	<context:component-scan base-package="com.orangeslate.naturestore">
		<context:exclude-filter type="annotation"
			expression="org.springframework.context.annotation.Configuration" />


Step 5: Creating a Test class

Here I have created a simple test class and initializing context inside using ClassPathXmlApplicationContext.

package com.orangeslate.naturestore.test;

import org.springframework.context.ConfigurableApplicationContext;

import com.orangeslate.naturestore.domain.Tree;
import com.orangeslate.naturestore.repository.NatureRepositoryImpl;
import com.orangeslate.naturestore.repository.Repository;

public class MongoTest {

	public static void main(String[] args) {

		ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(

		Repository repository = context.getBean(NatureRepositoryImpl.class);

		// cleanup collection before insertion

		// create collection

		repository.saveObject(new Tree("1", "Apple Tree", 10));

		System.out.println("1. " + repository.getAllObjects());

		repository.saveObject(new Tree("2", "Orange Tree", 3));

		System.out.println("2. " + repository.getAllObjects());

		System.out.println("Tree with id 1" + repository.getObject("1"));

		repository.updateObject("1", "Peach Tree");

		System.out.println("3. " + repository.getAllObjects());


		System.out.println("4. " + repository.getAllObjects());

Lets run it as Java application. We can see the below output. First method saves “Apple Tree” into the database. Second method saves “OrangeTree” also into the database. Third method demonstrates finding an object with its id. Fourth one updates an existing object name with “Peach Tree”. And at last; the last method deletes the second object from DB.

1. [Person [id=1, name=Apple Tree, age=10, category=null]]
2. [Person [id=1, name=Apple Tree, age=10, category=null], Person [id=2, name=Orange Tree, age=3, category=null]]
Tree with id 1Person [id=1, name=Apple Tree, age=10, category=null]
3. [Person [id=1, name=Peach Tree, age=10, category=null], Person [id=2, name=Orange Tree, age=3, category=null]]
4. [Person [id=1, name=Peach Tree, age=10, category=null]]

NOTE: You can download all this code from Github!


Creating Web Services using CXF (Contract first Approach) Part 2 : WSDL Creation.

What is WSDL and what its Structure?

A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations.

The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:

WSDL document describes a web service using these major elements:

Element Defines
<types> The data types used by the web service
<message> The messages used by the web service
<portType> The operations performed by the web service
<binding> The communication protocols used by the web service
<port> A single endpoint defined as a combination of a binding and a network address.
<service> A collection of related endpoints.

The main structure of a WSDL document looks like this:

definition of types……..

definition of a message….
definition of a port…….
definition of a binding….

definition of services….


A WSDL document can also contain other elements, like extension elements and a service element that makes it possible to group together the definitions of several web services in one single WSDL document.

Creating WSDL for our Example

<types>:In the Types we are defining or configuring the Datatypes which we are using for the entire application. Here we are importing the XSD files here.

<message>:In our example we need to configure our input and our parameters/ the message which we are passing through Webservice. We are configuring request and response objects here.

<portType>: We have one operation which is called getProduct. So here we need to declare this getProduct operation.

<binding> : Here we will be providing our protocol types and we are using SOAP protocol.

<service> : Defining the Service End point. And for the ProductService we are defining it as “http://localhost:8080/ContractFirst/services/ProductService


   1: <?xml version="1.0" encoding="UTF-8" standalone="no"?>
   2: <wsdl:definitions xmlns:soap=""
   3:     xmlns:tns="http://com/your/company/service/ProductService/" xmlns:wsdl=""
   4:     xmlns:xsd="" name="ProductService"
   5:     targetNamespace="http://com/your/company/service/ProductService/"
   6:     xmlns:prd="http://com/your/company/service/Product/">
   7:     <wsdl:types>
   8:         <xsd:schema targetNamespace="http://com/your/company/service/ProductService/"
   9:             xmlns:prd="http://com/your/company/service/Product/">
  10:             <xsd:import namespace="http://com/your/company/service/Product/"
  11:                 schemaLocation="../Product.xsd" />
  12:             <xsd:element name="getProductRequest">
  13:                 <xsd:complexType>
  14:                     <xsd:sequence>
  15:                         <xsd:element name="productRequest" type="prd:ProductRequest" />
  16:                     </xsd:sequence>
  17:                 </xsd:complexType>
  18:             </xsd:element>
  19:             <xsd:element name="getProductResponse">
  20:                 <xsd:complexType>
  21:                     <xsd:sequence>
  22:                         <xsd:element name="productResponse" type="prd:ProductResponse" />
  23:                     </xsd:sequence>
  24:                 </xsd:complexType>
  25:             </xsd:element>
  26:         </xsd:schema>
  27:     </wsdl:types>
  28:     <wsdl:message name="ProductRequest">
  29:         <wsdl:part element="tns:getProductRequest" name="parameters" />
  30:     </wsdl:message>
  31:     <wsdl:message name="ProductResponse">
  32:         <wsdl:part element="tns:getProductResponse" name="parameters" />
  33:     </wsdl:message>
  34:     <wsdl:portType name="ProductService">
  35:         <wsdl:operation name="getProduct">
  36:             <wsdl:input message="tns:ProductRequest" />
  37:             <wsdl:output message="tns:ProductResponse" />
  38:         </wsdl:operation>
  39:     </wsdl:portType>
  40:     <wsdl:binding name="ProductServiceSOAP" type="tns:ProductService">
  41:         <soap:binding style="document"
  42:             transport="" />
  43:         <wsdl:operation name="getProduct">
  44:             <soap:operation
  45:                 soapAction="http://com/your/company/service/ProductService/getProduct" />
  46:             <wsdl:input>
  47:                 <soap:body use="literal" />
  48:             </wsdl:input>
  49:             <wsdl:output>
  50:                 <soap:body use="literal" />
  51:             </wsdl:output>
  52:         </wsdl:operation>
  53:     </wsdl:binding>
  54:     <wsdl:service name="ProductService">
  55:         <wsdl:port binding="tns:ProductServiceSOAP" name="ProductServiceSOAP">
  56:             <soap:address
  57:                 location="http://localhost:8080/ContractFirst/services/ProductService" />
  58:         </wsdl:port>
  59:     </wsdl:service>
  60: </wsdl:definitions>

In our next part we will go through Skelton creation using WSDL to Java tool which is giving by CXF. We will go through class path settings and wsdl2java commands.

Creating Web services using Apache CXF (Part 1) : The Basics.

As we discussed in the previous post, CXF is the combination of two projects: Celtix developed by IONA and XFire developed by Codehaus working together at the Apache Software Foundation.



Apache CXF- An ultimate web service open source framework : Lets start learning…

Apache CXF is an open source services framework which is a result of the merge between the XFire and Celtix projects. CXF helps us build and develop services using JAX-WS. These services can speak a variety of protocols such as SOAP, XML/HTTP, RESTful HTTP, or CORBA and work over a variety of transports such as HTTP, JMS or JBI.

In this series we will go through two common approaches to create a web service.

  1. Code first approach
  2. Contract First approach

Spring Interview Questions Part: 1

  • What is mean by Dependency Injection? Or What do you mean by Inversion of Control?

Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC, although technically speaking, dependency injection specifically refers to an implementation of a particular form of IOC.

Dependancy Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor instead of creating one internally. The term "Dependency injection" is a misnomer, since it is not a dependency that is injected, rather it is a provider of some capability or resource that is injected. There are three common forms of dependency injection: setter-, constructor- and interface-based injection.

Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. This is often done by a lookup method. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing.

  • What are the modules in Spring?
  1. The core container:

    The core container provides the fundamental functionality of the Spring framework. In this module primary component is the BeanFactory, an implementation of the Factory pattern. The BeanFactoryapplies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code.

  2. Spring context module :

    TThe Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as e-mail, JNDI, EJB, internalization, validation, scheduling and applications lifecycle events. Also included is support for the integration with templating frameworks such as velocity.

  3. Spring AOP module:

    The Spring AOP module allows a software component to be decorated with additional behavior, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.

  4. Spring DAO module:

    The Spring DAO module provides a JDBC-abstraction layer that reduces the need to do tedious JDBC coding and parsing of database-vendor specific error codes. Also, the JDBC package provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces, but for all your POJOs (plain old Java objects).

  5. Spring ORM module:

    : Spring provides integration with OR mapping tools like Hibernate, JDO and iBATIS. Spring transaction management supports each of these ORM frameworks as well as JDBC.

  6. Spring Web module:

    The Web context module provides basic web-oriented integration features builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.

  7. Spring MVC framework module:

    Spring provides a pluggable MVC architecture. The users have a choice to use the web framework or continue to use their existing web framework. Spring separates the roles of the controller; the model object, the dispatcher and the handler object which makes it easier to customize them. Spring web framework is view agnostic and does not push the user to use only JSPs for the view. The user has the flexibility to use JSPs, XSLT, velocity templates etc to provide the view.

  • What is a BeanFactory and XMLBeanFactory?

Bean factory is a container. It configures, instantiates and manages a set of beans. These beans are collaborated with one another and have dependencies among themselves. The reflection of these dependencies are used in configuring data that is used by BeanFactory.

XMLBeanFactory is a bean factory that is loaded its beans from an XML file.

  • What are Inner Beans?

A bean inside another bean is known as Inner Bean. They are created and used on the fly, and can not be used outside the enclosing beans. The Id and scope attributes for inner beans are of no use.

  • What is DataAccessException?

DataAccessException is an unchecked RuntimeException. These type of exceptions are unforced by users to handle. This exception is used to handle the errors occurring when the details of the database access API in use, such as JDBC.

A review of “Spring Web Flow 2 Web Development” book from Packt.

About Spring Web Flow

Spring Web Flow allowing us to represent the UI flow in (part of) a web application in a clear and simple way. It has several advantages:

  • The UI flow in a web application is clearly visible by looking at the corresponding web flow definition (typically in an XML file).
  • Web Flows can be designed to be self contained. This allows you to see a part of your application as a module and reuse it in multiple situations.
  • Web Flows can define any reasonable UI flow in a web application, always using the same consistent technique. You’re not forced into using specialized controllers for very particular situations.

About this book:

“Spring Web Flow 2 Web Development” by Markus Stäuble, Sven Lüppken (from Packt) is a very good book to start with Spring Web flow. I got a chance to go through this book and I thought of writing a small review about this book in my page.

Just like the main well known Spring books, this book is also approaching learning by doing a small project.  In the entire book we are developing a small project (bug tracking system) and through that we are trying to learn web flow.

The source code for the book can be download from HERE .
Publisher: Packt Publishing (March 20, 2009)
Language: English


Authors: Markus Stäuble, Sven Lüppken

TO BUY THIS BOOK (Click on the Pic): 

Whats special in this Book?

  • The book is different in some cases like it does not only explain how to create flows with Spring Web Flow, but also shows the integration with other technologies like JavaServer Faces, EasyMock, Hibernate, Spring Security.
  • Explains web flow example project which is using so many other technologies, tools and frameworks like Maven/Ant, Eclipse/Netbeans IDE, Easymock, Apache Tiles etc etc.


  • More importantly it covers latest version and advantages of Spring Web Flow.
  • “Spring Web Flow 2 Web Development” is special in one case. They are started with the Installation and set-up of the whole environment. As a programmer it will help you very much. (although they are proving Code).
  • It starts from the very basics and moves on further.
  • Explains things with Maven/Ant, eclipse/Netbeans. This sounds very good.
  • This book explains the integration of Spring and Java Server Pages very clearly. And it  also explains the Spring web flow and Faces integration. This may consider an added advantage of this book.
  • Authors are given Class diagrams also for our reference in many framework class cases. This helps us to get a full idea about that class and the functionalities that provides.
  • It also also explains the essential modules of the complete Spring framework stack.
  • Given the complete configuration files and details of flows and others. This helps us to get the overall picture of the configurations.
  • Given so many reference links to follow. This also given at each specific parts of the book where that respective technology explains.
  • Explains Spring Java Script. It is really good to find some tutorial about that Library framework. Though it is coming through Spring Web Flow 2, a very few authors touches it in their books.
  • Another great advantage is it covers Spring Security. Gives us a chance to learn about this Library.
  • Apache Tiles integration and configuration is also covered although the book.
  • It also covers Unit testing of this Spring Web flow using EasyMock. This is really good point with respect to developers point of view.
  • It gives us an idea about running in the SpringSource dm Server (modular OSGi -Open Services Gateway initiative).


  • In the installation chapter we are coming across a lot of frameworks/tools. If you are a person who knows most of them then that chapter will be easy for you. Otherwise you need a bit more time to understand that.
  • Missing Spring IDE explanation.
  • Not much information about Spring basics. That’s seems to be Okay because they mentioned it as a book for the people who knows Spring.
  • The code mentioned in the book follows the same font. If they would have make the syntax/code highlighted/with some sort of separation  then that would have been great to read.
  • One basic thing about the formatting. Paragraphs are not JUSTIFIED. May be  that affects the code snippets. But surely this is making a bit bad look for the entire book in my view.

A really good Spring book from Packt! “Spring Web Flow 2 Web Development”

Spring Web Flow Book from Packt

If you know Spring Application Framework and keen to study its Web Strength specially its MVC and Web flow then this book will be a really better way for that. Packt published its latest book regarding one of the key member of Spring Family; “Spring Web Flow 2“.  It covers a lot many things like Spring Faces ( Specially its inegration with JSF), Spring Web Flow (With its very Latest version) and Spring Security…The key point about the book is, it describes everything, starting from the basics like Installing and configuring the web flow to its unit testing. 

Do visit the home of  this  book from Packt through this link. Click here

Find out the Table of contents here. You can also do a free download of one Chapter.