Spring Core Hello World example

Here is a very simple spring core hello world example that will guide you to learning the spring in an easy way. The following example will contain two simple classes and an xml file which makes it easy for you to understand the very large concepts of spring.

1. Download Spring framework


Many of the developers use maven, a tool that will automatically download the necessary jar files for a project. But in this tutorial, I'll not be using maven instead, the theme of the tutorial is to teach spring and not maven with spring, I suggest manually downloading the jar files so that you'll get a better idea of what jar files you require for your project. However, at real time it is recommended to use a tool like the maven.

http://repo.spring.io/release/org/springframework/spring/

In the above link, you will be provided with several versions of spring. Download the latest version possible. Download those that end with -dist.zip because these files contain the jar files that we need for our project.
After downloading extract them to a location. You will also need commons-logging because spring uses it for logging purposes.

http://commons.apache.org/proper/commons-logging/download_logging.cgi

Till now, in this blog, we have seen writing programs in Notepad and then compiling them and executing them in the command prompt. While this is a good practice for starters, I recommend using Eclipse (the most popular IDE for Java developers) to continue with the Spring because a developer, in real time environment will be using an IDE to write programs. Hope you will embrace this change.

2. Create a project in eclipse

So, I'll be naming the project as spring1 since this is the first demo. Note that I haven't used STS (Spring Tool Suite) which most will probably be using. Rather, I have just downloaded the required jar files we need to create our project and included them in the library. Therefore, we will be carrying on creating a simple eclipse project and adding the necessary spring jars. I am using Eclipse JUNO.

  1. File -> New -> Project -> Java Project
  2. Give the project name spring1 and click Finish 
  3. Now, the project is created.
  4. Under the Project Explorer (in the sidebar) you will see spring1. If you aren't able to see Project Explorer, go to Window menu -> Show view -> Project Explorer.
  5. Right click on the spring1 and click Properties
  6. On the left side, click on Java Build Path.
  7. Select the Libraries tab and then click on Add External Jars
  8. Now, add these jar files starting with: spring-beans, spring-context, spring-core, spring-expression, commons-logging
  9. Click on OK and then you are ready.
 

Simple bean - Message.java

A bean is nothing more than a class that represents a particular entity. This class will contain details about that entity which can be accessed using its object.

package spring1;

public class Message {

private String message;

    public void setMessage(String message)
    {
        this.message=message;
    }
   
    public String getMessage()
    {
        return message;
    }
}

The class contains setMessage() which is used to set the message and getMessage() which is used to get the message.

Main class - SpringPrg.java

This class will contain the main method and here we will be getting the object of Message class from the factory.

package spring1;

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

public class SpringPrg {
    public static void main(String[] args)
    {
        ApplicationContext ctx=new ClassPathXmlApplicationContext("spring1/context.xml");
        Message m=(Message)ctx.getBean("message");
        System.out.println(m.getMessage());
    }
}

Here ApplicationContext is an interface that is implemented by ClassPathXmlApplicationContext class. This class will take an XML file which will contain how bean objects are created. According to this, the spring container creates the bean objects and gets them for us.

The advantage of getting a bean object from the container is that, the container reads the xml file and creates the object according to the procedure mentioned in that file. So, if you would like to change the way you create the object, for example, if you want to use a different constructor, then you need not change the code of your Java program, you'll only need to change that in the xml file. Therefore, you will remove the burden of recompiling the class file every time you want to change the message or use a different constructor.
Also, sometimes you might need to create a lot of objects for use in different classes. So at that time, you'll probably write the creation code like this.

Message m=new Message();
m.setMessage("Hello world!");

Two lines of code, every time you want to use it in a class. It will be a problem, especially if you have 100+ classes that will use this object and therefore you will need to write 200 lines of code. In some cases, object creation might take 5 lines or more , so you'll need to write 500 extra lines of code. For example,

A a=new A();
B b=new B();
C c=new C();
D d=new D();
X x=new X(a,b,c,d);

Application Context - context.xml

<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">

    <!-- Create object for spring1.Message with name message -->
    <bean id="message" class="spring1.Message">
   
        <!-- Call message.setMessage("Hello world!") -->
        <property name="message" value="Hello world!"/>
   
    </bean>

</beans>

This is an XML file which you might have undergone several times. The <beans> tag contains several bean definitions i.e. how those bean object has to be created. A bean here is a class.

xmlns: This stands for xml namespace. When you declare xmlns="" means that it is the default namespace. Here the only namespace we are using is beans.
xsi:schemaLocation : Specifies the location of the schema. The http://www.springframework.org/schema/beans/spring-beans-3.0.xsd file contains definitions for the <beans> and <bean> tag and so on.

You can give this file any name you want but make sure that the same name is passed in the ClassPathXmlApplicationContext.

No comments: