How To Resolve com.owlike.genson.stream.JsonStreamException: Illegal character at row 0 and column 1 expected } but read ”’ !

While dealing with JSON data you may sometimes run into following kind of error –

Caused by: com.owlike.genson.stream.JsonStreamException: Illegal character at row 0 and column 1 expected } but read ”’ !
at com.owlike.genson.stream.JsonReader.newWrongTokenException(JsonReader.java:951)
at com.owlike.genson.stream.JsonReader.end(JsonReader.java:437)
at com.owlike.genson.stream.JsonReader.endObject(JsonReader.java:179)
at com.owlike.genson.reflect.BeanDescriptor.deserialize(BeanDescriptor.java:113)
at com.owlike.genson.reflect.BeanDescriptor.deserialize(BeanDescriptor.java:92)
at com.owlike.genson.convert.NullConverter$NullConverterWrapper.deserialize(NullConverter.java:56)
at com.owlike.genson.Genson.deserialize(Genson.java:389)

Usually this is caused by JSON object having single quotes.  For example if you have a JSON with the following structure

{'books':
   [
	{
	  'name':'My Experiments With Truth',
	  'serialNumber':3
     },
     {
       'name':'Deep Work',
	   'serialNumber':4
     },
     {
       'name':'So Good They Cannot Ignore You',
	   'serialNumber':5
     }
   ],
 'totalPrice':100
}

… and it is sent to a REST web service like the example here, you will get the above error.  The reason is very simple.  As you can notice the field names are enclosed in single quotes.  For example you can see ‘name’:’My Experiments With Truth’,  name and the value are enclose in single quotes.

To solve it put the values in double quotes.  Here is how the JSON should be.

{
 
 "books": [
  {
    "name": "Head First Java",
    "serialNumber": 1
  },
  {
    "name": "Head First Design Pattern",
    "serialNumber": 2
  },
  {
    "name": "My Experiments With Truth",
    "serialNumber": 3
  }],
  "totalPrice" :100
}

References – http://stackoverflow.com/questions/14355655/jquery-parsejson-single-quote-vs-double-quote

How To Post JSON List To REST Service As ArrayList

In the previous tutorial we saw how to POST XML List to a Jersey REST web service as ArrayList.  We sent a simple xml structure which represented a book.  What about sending a JSON list instead of XML list?

In this tutorial we will learn how to send a list of books in JSON format to the REST service using POST method.  The JSON List will be contained in a structure which will map to Books class as you can see below.

The service should accept the books sent and add them to the book list available in the system.  The service will then return back a list which contains pre-existing books in the system along with the books sent to the service.

Here is How the Service works

The REST service takes a list of Book objects and their price in a Books object in JSON format using POST method.  Although the totalPrice of books is sent it is mainly for demonstration purpose.  The price is not processed.  It is sent just to show that we can send other elements along with book list.

The service is annotated with @POST so that POST method can be used from the client.  This service takes JSON data as input and it gets converted to Books object which has structure to match the JSON input.  The Books class is a container class which contains list of book objects and a price field.

Service then retrieves a list of books from a utility class and adds the books sent to the method.  Then the list is sent back to the client.

To create a list of books a utility method has been created in the BookCreator class.  That class simply returns a list which contains two Book objects.

To receive the book as JSON two things are needed.

The input JSON should be mapping to the structure of the Books class.  You will see the example below.  The Content-Type should be application/json.

 

PostXmlService.java

package com.freetipscentral;
 
import java.util.List;
 
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
 
import com.freetipscentral.domain.Book;
import com.freetipscentral.domain.Books;
import com.freetipscentral.utility.BookCreator;
 
@Path("/postXML")
public class PostXmlService {
 
	@Produces(MediaType.APPLICATION_JSON)
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public List<Book> getBookAsJSON(Books books) {
		List<Book> bookList = BookCreator.getBooks();
		bookList.addAll(books.getBooks());
 
		return bookList;
	}
}

Book.java

package com.freetipscentral.domain;
 
public class Book {
 
	String name;
	int serialNumber;
 
	public Book() {}
 
	public Book(String name, int serialNumber) {
		this.name = name;
		this.serialNumber = serialNumber;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public int getSerialNumber() {
		return serialNumber;
	}
 
	public void setSerialNumber(int serialNumber) {
		this.serialNumber = serialNumber;
	}
 
	public String toString() {
		return serialNumber + " "  + name;
	}	
}

Books.java

[codesyntax lang=”java”]

package com.freetipscentral.domain;

import java.util.List;

public class Books {
	
	List<Book> books;
	int totalPrice;
	
	public List<Book> getBooks() {
		return books;
	}
	public void setBooks(List<Book> books) {
		this.books = books;
	}
	public int getTotalPrice() {
		return totalPrice;
	}
	public void setTotalPrice(int totalPrice) {
		this.totalPrice = totalPrice;
	}
		
}

[/codesyntax]

BookCreator.java

package com.freetipscentral.utility;
 
import java.util.ArrayList;
import java.util.List;
 
import com.freetipscentral.domain.Book;
 
public class BookCreator {
 
	public static List<Book> getBooks() {
		List<Book> books = new ArrayList<Book>();
		Book book1 = new Book("Head First Java",1);
		Book book2 = new Book("Head First Design Pattern",2);
		books.add(book1);
		books.add(book2);
		return books;
	}
 
}

Here is the input Body

{
 
 "books": [
  {
    "name": "Head First Java",
    "serialNumber": 1
  },
  {
    "name": "Head First Design Pattern",
    "serialNumber": 2
  },
  {
    "name": "My Experiments With Truth",
    "serialNumber": 3
  }],
  "totalPrice" :100
}

Input Header

Content-Type  application/json

Here is the Output

[
 {
 "name": "Head First Java",
 "serialNumber": 1
 },
 {
 "name": "Head First Design Pattern",
 "serialNumber": 2
 },
 {
 "name": "Head First Java",
 "serialNumber": 1
 },
 {
 "name": "Head First Design Pattern",
 "serialNumber": 2
 },
 {
 "name": "My Experiments With Truth",
 "serialNumber": 3
 }
]

Here is the Video version of this tutorial

How to POST XML List To REST Service As ArrayList

In one of the previous tutorials we saw how to POST XML data to a Jersey REST webservice.  We sent a simple xml structure which represented a book.  In this tutorial we will learn how to send a list of books to the REST service using POST method.  The service should add the books sent to the service and then return back a list which contains pre-existing books in the system along with the books sent to the service.

Here is how the service works

The REST service takes a list of Book objects as XML using POST method.  The input also contains price of the books.  The price is not processed.  It is sent just to show that we can send other elements along with book list.

The service is annotated with @POST so that POST method can be used from the client.  This service takes Xml data as input and it gets converted to Books object which has structure to match the XML input.  The Books class is a container class which contains list of book objects and a price field.  It matches with the input from the XML.

Service then retrieves a list of books from a utility class and adds the books sent to the method.  Then the list is sent back to the client.

To create a list of books a utility method has been created in the BookCreator class.  That class simply returns a list which contains two Book objects.

To receive the book as XML two things are needed.

The Books class should be annotated with following –

@XmlRootElement(name =”books”)

The name attribute attribute indicates that the root element the xml data sent from the client should be named “book”.

The Book class

should be annotated with following –

@XmlRootElement(name =”book”)

Here are the classes you need.

PostXmlService.java

package com.freetipscentral;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.freetipscentral.domain.Book;
import com.freetipscentral.domain.Books;
import com.freetipscentral.utility.BookCreator;

@Path("/postXML")
public class PostXmlService {

  @Produces(MediaType.APPLICATION_XML)
  @POST
  @Consumes(MediaType.APPLICATION_XML)
  public List<Book> getBookAsXMLList(Books bookSet) {
    List<Book> books = BookCreator.getBooks();
    books.addAll(bookSet.getBooks());
    
    return books;
  }
}

Book.java

package com.freetipscentral.domain;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name ="book")
public class Book {
  
  String name;
  int serialNumber;
  
  public Book() {}
  
  public Book(String name, int serialNumber) {
    this.name = name;
    this.serialNumber = serialNumber;
  }
  
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getSerialNumber() {
    return serialNumber;
  }

  public void setSerialNumber(int serialNumber) {
    this.serialNumber = serialNumber;
  }

  public String toString() {
    return serialNumber + " "  + name;
  }	
}

Books.java

The Books class should have @XmlElement(name=”book”) annotation for the books field which is the ArrayList of Book class.  This part is crucial.  This tells that books field maps to “book” element in the XML.  It also needs @XmlRootElement(name =”books”) at the class level.  The class should also be annotated with  @XmlAccessorType(XmlAccessType.FIELD) so as to avoid conflict for the annotating book.

package com.freetipscentral.domain;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name ="books")
@XmlAccessorType(XmlAccessType.FIELD)
public class Books {
  
  @XmlElement(name="book")
  List<Book> books;
  int totalPrice;
  
  public List<Book> getBooks() {
    return books;
  }
  public void setBooks(List<Book> books) {
    this.books = books;
  }
  public int getTotalPrice() {
    return totalPrice;
  }
  public void setTotalPrice(int totalPrice) {
    this.totalPrice = totalPrice;
  }
  
  
}

BookCreator.java

package com.freetipscentral.utility;

import java.util.ArrayList;
import java.util.List;

import com.freetipscentral.domain.Book;

public class BookCreator {
  
  public static List<Book> getBooks() {
    List<Book> books = new ArrayList<Book>();
    Book book1 = new Book("Head First Java",1);
    Book book2 = new Book("Head First Design Pattern",2);
    books.add(book1);
    books.add(book2);
    return books;
  }

}

Here is the input Body

<books>
  <book>
  <name>The law of Karma</name>
  <serialNumber>3</serialNumber>
  </book>
  <book>
  <name>Freedom at midnight</name>
  <serialNumber>4</serialNumber>
  </book>
  <book>
  <name>Deep Work</name>
  <serialNumber>5</serialNumber>
  </book>
  <totalPrice>100</totalPrice>
</books>

 

 

Input Header

Content-Type  application/xml

Here is the Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<books>
    <book>
        <name>Head First Java</name>
        <serialNumber>1</serialNumber>
    </book>
    <book>
        <name>Head First Design Pattern</name>
        <serialNumber>2</serialNumber>
    </book>
    <book>
        <name>The law of Karma</name>
        <serialNumber>3</serialNumber>
    </book>
    <book>
        <name>Freedom at midnight</name>
        <serialNumber>4</serialNumber>
    </book>
    <book>
        <name>Deep Work</name>
        <serialNumber>5</serialNumber>
    </book>
</books>

Here is the Video version of this tutorial

 

How To Resolve 400 Bad Request While Posting XML Data to REST Service

While writing a REST service to accept XML  as the POST data you could run into the following problem while submitting XML data – HTTP Status 400 – Bad Request.  If you see https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html you will see that 400 Bad request means Server is not able to serve the request due to malformed request from the client.  You can find example of how to post xml data to a REST service here.

In that example there was a Book class which was annotated as follows –
@XmlRootElement (name = “book”)
public class Book {

}

The input xml sent should be similar to following –

<book>
  <name>My Experiments With Truth</name>
  <serialNumber>3</serialNumber>
</book>

When the XML data is submitted it is converted to Book Object.  Here are some scenarios when you may get 400 bad request.

  1. If the xml root element is not <book>.  For example if the root element is <Book> it will throw bad request exception.  The reason is the mapping on the Book class expected <book> to be the root element.
  2. You may remove the (name = “book”> from the Book class and still it will work for <book>.  The reason is small case element name for the class name will work.
  3. If you want to use <Book> or any other element name such as <Novel> then you need to add it as attribute in the Book class annotation.  For example you can annotate the book class as follows

@XmlRootElement (name = “Book”)
public class Book {

}

In this case REST service can be called with following request data.

<Book>
  <name>My Experiments With Truth</name>
  <serialNumber>3</serialNumber>
</Book>

 

or

@XmlRootElement (name = “Novel”)
public class Book {

}

The the following XML should be sent.

<Novel>
  <name>My Experiments With Truth</name>
  <serialNumber>3</serialNumber>
</Novel>

 

 

How To Post XML Data With POST Method in REST Service

The most popular data structure to submit data with POST method to a REST service is JSON.  However you may still need to post XML data.  Let us see how to do that.  Lets see how you can POST XML data with Jersey REST service.

The REST service takes a Book object using POST method.  That is done using @POST annotation.  This service takes Xml data as object and it gets converted to Book object.   Service retrieves a list of books.  To create a list of books a utility method has been created in the BookCreator class.  That class simply returns a list which contains two Book objects.  The book received from the client is added to the list and the book is then returned back.

To receive the book as XML two things are needed.

The Book class should be annotated with following –

@XmlRootElement(name =”book”)

The name attribute attribute indicates that the root element the xml data sent from the client should be named “book”.

When the XML is sent, the make sure that the XML structure has elements present in the book class.

Here are the classes you need.

PostXmlService.java

package com.freetipscentral;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.freetipscentral.domain.Book;
import com.freetipscentral.utility.BookCreator;

@Path("/postXML")
public class PostXmlService {

  @Produces(MediaType.APPLICATION_XML)
  @POST
  @Consumes(MediaType.APPLICATION_XML)
  public Book getBookAsJSON(Book book1) {
    List<Book> books = BookCreator.getBooks();
    books.add(book1);
    
    return book1;
  }
}

Book.java

package com.freetipscentral.domain;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name ="book")
public class Book {
  
  String name;
  int serialNumber;
  
  public Book() {}
  
  public Book(String name, int serialNumber) {
    this.name = name;
    this.serialNumber = serialNumber;
  }
  
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getSerialNumber() {
    return serialNumber;
  }

  public void setSerialNumber(int serialNumber) {
    this.serialNumber = serialNumber;
  }

  public String toString() {
    return serialNumber + " "  + name;
  }	
}

BookCreator.java

package com.freetipscentral.utility;

import java.util.ArrayList;
import java.util.List;

import com.freetipscentral.domain.Book;

public class BookCreator {
  
  public static List<Book> getBooks() {
    List<Book> books = new ArrayList<Book>();
    Book book1 = new Book("Head First Java",1);
    Book book2 = new Book("Head First Design Pattern",2);
    books.add(book1);
    books.add(book2);
    return books;
  }

}

Here is the input Body

<book>
  <name>My Experiments With Truth</name>
  <serialNumber>3</serialNumber>
</book>

Input Header

Content-Type  application/xml

Here is the Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book>
    <name>My Experiments With Truth</name>
    <serialNumber>3</serialNumber>
</book>

Here is a Video Tutorial I created for the above steps

How To Configure STS To Use Proxy Server

If you use STS (Eclipse Kepler) behind a firewall it can prevent you from downloading eclipse plugins or patches.  To be able to connect to Eclipse Market Place or Link to install new software you would need to tell STS about the proxy server.  Proxy servers are usually the way to access outside network when in company network.  There are two ways to have proxy server.

Here are the steps if you do it from STS.

  1. Windows -> Preferences -> General -> Network Connectivity
  2. In the Active Provider Drop down, select Manual.
  3. You can see HTTP and HTTPS schema.  Click on the Edit button.  You can see the followingProxy setting in Eclipse
  4. Add the proxy server host name or ip address and the port number. Click OK to save.  Similarly add for HTTPS also.
  5. Now you can try to access the Eclipse Market place and see if that works.
  6. In case it does not work there is another way to set the proxy server.  Go to the STS installation directory and edit the STS.ini.
  7. Add the following entries

-Dhttp.proxyPort= port number of the proxy server
-Dhttp.proxyHost=proxy server host name

Save the file and restart the STS.  You should now be able to access the eclipse marketplace through the STS.

How To Add Support For Java 8 in STS (Kepler)

If you are using STS or Keplet on which it is based previous to 3.5.1 version and install JDK 8 you may not be able to use Java 8.  To be able to use Java 8 your eclipse needs Java 8 patch.  In this tutorial I will show how to install Java 8 patch.  Here are the steps.

  1. Of course you need to install JDK 8.   Next set the JAVA_HOME system variable to Jdk 8 install directory.
  2. Next click on Help -> Eclipse Marketplace…
  3. Eclipse Marketplace wizard will open and in the search box type Java 8 kepler (STS uses Kepler Eclipse).  Press enter and it will bring up options as you can see in the screen shot below.  In case eclipse is not able to connect to marketplace the proxy server setting may be required. For that you can read how to setup proxy server in STS tutorial.

java8sts

4. The following are required –

  • Java 8 facet for web tools for Eclipse Kepler SR2
  • Java 8 support for  Eclipse Kepler SR2
  • Java 8 support for m2e for Eclipse SR2 (See the screenshot below)

java8sts2

5. Select the first option and Click Install. It will show a pop up with Confirm Selected Features.  Since we want to select more click on <Install More.  It will go back to the previous screen and now you can select the other two.  Click on Install Now>.  Click confirm.

6. Software installation will start as below.

java8sts3

7.  Once installation is done STS needs to be restarted.  You will get a screen as below.  Click on Yes.

java8sts4

8.  Once STS restarts you can confirm if STS has access to Java 8 by following steps.  Windows -> Preferences -> Java -> Compiler.  You should now be able to see 1.8 for the Compiler compliance level:

java8sts5

Happy coding.

How To Resolve 405 – Method Not Allowed While Calling REST Service

Discipline is the bridge between goals and accomplishment. ~ Jim Rohn

One of the common errors you might encounter while accessing REST services is 405 Method Not Allowed error.  So what does this mean?  And how can you resolve it?

What Does 405 – Method Not Allowed means?

To understand this you need to know little bit about HTTP methods.  There are four basic HTTP methods.  GET, POST, PUT and DELETE.  There are other methods but these are the common ones.  Out of these four the GET and PUT methods are most frequently used.

REST services communicate with client on HTTP protocol and client uses one of these methods to make a service call.  Usually if you want to fetch some data from the server you will use GET method.  So save some data POST method is used.  PUT is used for update if found else insert data.  DELETE is used to delete data from the server.

The method which is served by the REST service is mentioned at the service code.  The client accessing the service should call the service with the same coded.

For example if there is a GET method for a service, the client should also send GET request for the URI.  If the method sent by the client is not the same as the server then 405 Method Not Allowed exception is returned to the client.  This is not only specific to REST.  It is part of HTTP specification.

Here is an example

package com.freetipscentral;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.freetipscentral.domain.Book;

@Path("/getResponseJSON")
public class RestJSONResponseService {

  @GET
  public Response getBookAsXML(@Context HttpHeaders httpHeaders) {
    
    Book book1 = new Book("Head First Java", 1);
    
    return Response.ok(book1,MediaType.APPLICATION_XML).build();
  }
}

As you can see above the service expects to be called with GET method as it is annotated with @GET method.

If the above service is called with any other method such as POST or PUT you will see the following exception.

<html>
    <head>
        <title>Apache Tomcat/7.0.65 - Error report</title>
        <style>
            <!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}-->
        </style>
    </head>
    <body>
        <h1>HTTP Status 405 - Method Not Allowed</h1>
        <HR size="1" noshade="noshade">
        <p>
            <b>type</b> Status report
        </p>
        <p>
            <b>message</b>
            <u>Method Not Allowed</u>
        </p>
        <p>
            <b>description</b>
            <u>The specified HTTP method is not allowed for the requested resource.</u>
        </p>
        <HR size="1" noshade="noshade">
        <h3>Apache Tomcat/7.0.65</h3>
    </body>
</html>

How To Resolve 405 Method Not Allowed

You would usually need to change the method with which you are calling the service.  If you own the service code then you can look up the method and see the method such as GET  or PUT and call with that method.  If you are calling a third party service you can look up the documentation and then call with that method.

How To Create Spring 4.3 Hello World Application With Maven

In the previous article we saw how to create Hello World Spring 4.3  Java application.  In this tutorial let us see how to create a hello world Java application with Maven.  In the last example we had to manually download the Spring jars and attach it to the project.  However making sure all the dependencies are present is a big problem.  Here is where Maven can help us.

Prerequisites – Your computer should have maven installed.

Steps

Create Maven Archetype project with Eclipse Maven plugin.

File > New > Maven Project

The below window should appear.  Select Next.

mavenproj1

In the pop up select maven-archetype-quickstart and click Next
mavenproj2

In the next screen select Group id as com.freetipscentral and Artifact id as HelloWorld and click Finish.  You will see that a project is created with the name HelloWorld.

maven proj 3

Open the HelloWorld.  There will be a pom.xml  file.  Open the file and add the following dependency.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.freetipscentral</groupId>
  <artifactId>HelloWorld</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>HelloWorld</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>


  </dependencies>
</project>

As soon as you save the file maven dependencies will be downloaded.  You will see the following dependencies

workspace structure

The App.java is generated automatically.  However you need the following files.

HelloWorld.java

package com.freetipscentral.HelloWorld;

public class HelloWorld {
  public void sayHello(){
    System.out.println("Hello World");
  }
}

TestHelloWorld.java

package com.freetipscentral.HelloWorld;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestHelloWorld {
  public static void main(String args[]){
    // create and configure beans
    ApplicationContext context =
        new ClassPathXmlApplicationContext("config.xml");
    // retrieve configured instance
    HelloWorld firstBean = (HelloWorld)context.getBean("helloWorld");
    firstBean.sayHello();
  }
}

config.xml

<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
  <bean class="com.freetipscentral.HelloWorld.HelloWorld" id="helloWorld">
  </bean>
</beans>

When you run TestHelloWorld.java you get the following output

 

Sep 16, 2016 10:03:59 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4d405ef7: startup date [Fri Sep 16 22:03:59 CDT 2016]; root of context hierarchy
Sep 16, 2016 10:03:59 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [config.xml]
Hello World

Creating a Hello World program in Spring 4.3 with Eclipse

Perfection is not attainable, but if we chase perfection we can catch excellence. ~ Vince Lombardi

Hello World programs are usually the first steps in learning any new technology. Though the programs are simple are rarely do anything significant, they are important from two angles.

a) Your IDE becomes ready for more complex programs because of the setup/configuration you need to perform before you are able to run the Hello World program.

b) It gives you a real feel of though minuscule, how the technology works.

Thus it is important that you create a small program and execute it once you gain the preliminary knowledge of any Technology.  Here is a simple program and steps for how to set it up.  The IDE I have used for this example is Eclipse which is one of the most popular IDEs.

The preferred way is to go for Maven or Gradle.  However for this tutorial I will show how to do the setup with the distribution directly.

Before you start remember to download Spring and unzip it in a directory.  You can download spring framework from https://projects.spring.io/spring-framework/.  Select the version and download the distribution.  Usually you can go for the latest build.

Step 1 : Create a Java Project.

  • Click the following : File NewJava Project
  • In the project name mention “SpringTest”. Click Next
  • Click the Libraries Tab. Click “Add External Jars” button.
  • Now the file browser go to the directory where Spring jars are present. Usually it is “lib” directory under the spring unzip directory. Though you may not need to add all the jar for a hello world program, they will be useful when you create more complex examples using the more advanced features of Spring.  Just select the “RELEASE” versions.
  • You also need commons-logging-1.2.jar. You can download them from  https://commons.apache.org/proper/commons-logging/download_logging.cgi

Step 2 : Create the Files

a) Under the src create a file : “config.xml”.  Here is the content.

<beans xmlns="http://www.springframework.org/schema/beans" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
 <bean class="com.freetipscentral.HelloWorld" id="helloWorld">
 </bean>
</beans>

This xml file is the Spring configuration file which our application will use.  We declare a bean with id “helloWorld” which refers to HelloWorld class.

b) Create a package.  Right click on src folder and select New > Package .  Name it “com.freetipscentral

c) Create a Java file and name it as “HelloWorld.java” under the “com.freetipscentral” package.  This is a simple java file with just one method sayHello(). Here is the code.

package com.freetipscentral;

public class HelloWorld {
 public void sayHello(){
 System.out.println("Hello World");
 }
}

 

d) Create another Java file “TestHelloWorld.java” under the “com.freetipscentral” package.  This file contains main method.  In the method load we first load the configuration file which create the bean container.  Next, we just access the bean from the container and call the sayHello method.  Here is the code for that.

package com.freetipscentral;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestHelloWorld {
 public static void main(String args[]){
 // create and configure beans
 ApplicationContext context =
 new ClassPathXmlApplicationContext("config.xml");
 // retrieve configured instance
 HelloWorld firstBean = (HelloWorld)context.getBean("helloWorld");
 firstBean.sayHello();
 }
}

Step 3 : Run the Example
This is the simplest step. Right click on “TestHelloWorld.java” > Run As > Java Application. You should see the following output.

INFO: Loading XML bean definitions from class path resource [config.xml]
Hello World