Getting started with Spring Framework

Getting started with Spring Framework
This illustrates first Spring Hai application which would kickstart your Spring journey. Spring is one of the best frameworks used in the industry which not just provides an abstraction layer on a particular core technology, instead it provides and supports many technologies. It is a Java/JEE framework and not just a web framework. The following is a simple application that let's you get started.



What is Spring? Why use it?

Spring is an all in one framework that can be used to handle Model, View, Controller. It simplifies the core technologies and other frameworks by abstraction. For instance, JDBC is simplified so that their is no need to load the driver class and create a connection object while this is done, it is not done by the programmer (done internally). It is enough if you specify driver class, url, username, password separately in a configuration file and the connections will be in the pool and so you can access them easily.

Spring simplifies application development. It can be used to write business logic. persistence logic, presentation logic and the controller logic. However as far as the industry standards are concerned, Spring is mostly used to develop business logic of the application. It is a vast topic in fact and that is obvious too. Remember that it is not necessary that you make use of every module that is provided by the Spring framework. You can develop applications from scratch (0%) using Spring framework. It supports POJO and POJI model programming as you can see in the below example.

The Spring Framework has several modules which will be discussed in another post for the sake of brevity.

1. Create the Configuration file

Create an XML file that contains everything that the Spring Container needs to know such as bean definitions and data to be injected into the bean class' variables. This XML file consists of bean class, parameters to constructors, values to be passed to the setter methods.

1.1 What is spring container?

It is a class that reads the spring configuration file and performs respective operations as per the specification. For instance, instantiating the bean class, injecting data into the bean class' variables. This is a light weight component unlike a servlet container.

2. Create the interface and Bean class

Creating an interface is entirely optional but it is recommended to do so. A bean class can handle lot of different data and there must be a way to classify it. The Bean class is a POJO class i.e. the class which is not in relationship with the framework's classes or interfaces. However it can have an is-a relationship with the core technologies (i.e. core classes/interfaces that come with Java, say java.io.Serializable) for example. So this class can implement an interface which is not a part of the Spring or other framework (non-core technology). A part from classification of data, interfaces has another use here which you'll encounter later in this article.

The Bean class here contains setter and getter methods which are capable of setting and getting the values in/from the data member variables of the class respectively. It can also contains some additional methods that can extend it's functionality. In this article, you'll come to know how a Bean class might look.

3. Creating the main program.

Here is the main thing. Now that, you've completed writing the XML file, interface and the Bean class. Now there must be a way to ensure that these are used. You'll need to make use of both of these and put them for work. So you need one more program which will put them in work. You need a Spring Container that will do the task and that can be created in this program. In this post, you'll come to know about it.

Stepping into the program

Folder structure

Application folder E:\java\spring\springapp1


springapp1
         |_ myconfig.xml
         |_ Demo.class
         |_ DemoBean.java
         |_ DemoBean.class
         |_ Client1.java
         |_ Client1.class

 A. myconfig.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-3.0.xsd">

    <bean id="dm" class="DemoBean">
        <property name="name" value="Gowtham Gutha"/>
    </bean>
</beans>

B. Bean class and interface


interface Demo
{
    public String greet();
}

class DemoBean implements Demo
{
private String name;
       
    public void setName(String name)
    {
    this.name=name;
    }
   
    public String getName()
    {
    return name;
    }

    public String greet()
    {
    return "Hai "+name;
    }
}

C. Creating the main program (client)


import org.springframework.core.io.*;
import org.springframework.beans.factory.xml.*;
class Client1
{
    public static void main(String args[])
    {
   
    FileSystemResource resource=new FileSystemResource("myconfig.xml");

    XmlBeanFactory factory=new XmlBeanFactory(resource);

    Demo d=(Demo)factory.getBean("dm");
   
    System.out.println(d.greet());
    }
}


Program Output


May 6, 2013 12:55:43 PM org.springframework.beans.factory.xml.XmlBeanDefinitionR
eader loadBeanDefinitions
INFO: Loading XML bean definitions from file [E:\java\spring\springapp1\myconfig
.xml]
Hai Gowtham Gutha

Explaining the application

myconfig.xml

Here the configuration file starts with the <beans> tag which has some mandatory attributes helpful for the Spring container to know that these tags exist and how they work.

The next tag is <bean>. This tag here takes two attributes one is the id and another one is the class.
The id represents the identity of the bean class specified in the class attribute. The use of id is that, it is used to get the associated class' object using getBean() method in XmlBeanFactory class.

A Bean generally has properties. They are nothing but the name, value pairs. These are the variables for which the setter and getter methods are written. If you can observe, the property tag takes in the name of the attribute and it's value. The property name represents the name member variable in the DemoBean class and the value Gowtham Gutha is injected into the name member variable.

As we have only one property of the bean class, there is only one property tag written for it. For multiple properties, multiple tags will be needed.

Remember that the <property> tag is written with in the <bean> tag. The reason is obvious here. Here we are setting properties for the DemoBean class.

Bean Class and Interface

You might ask me, why write an interface. As said earlier that it is for obvious classification. One more reason is that we can use the reference of this interface to call the methods in it that are implemented in the class that implements the interface. We know that, object for an interface is nothing but the object for the class that implements that interface. So as the class is implementing the interface, it contains body for the abstract methods specified in the interface and hence we can call them using interface reference. You'll encounter this while discussing Client1 class.

The Interface Demo consists of only single method greet() which returns a String.
The DemoBean class implements Demo and this class contains a property name of type String.
The value to this property is set internally using the setter method setName(String) and retrieved using getName() if we wish to.
The greet() method from the Demo interface is implemented here which returns the name preceded by Hai.

Client1.java

This is the class that you have to execute. While compiling use javac *.java which compiles all files. org.springframework.core.io.*: It contains FileSystemResource class which is used here.
org.springframework.beans.factory.xml.*: It contains XmlBeanFactory class which is used here.

resource=new FileSystemResource("myconfig.xml"): Points out to the spring configuration file. This class internally uses the java.io.File. Complete path or relative path of the file can be given here as parameter.

new XmlBeanFactory(resource): The constructor of XmlBeanFactory takes FileSystemResource and parses the XML file associated with the FileSystemResource object using SAXParser. The XML file is verified by the Spring Container which is activated by this statement.

Demo d=(Demo)factory.getBean("dm"); This statement returns the object of the class associated with the bean id dm from the configuration file that this factory object points out to. You can note that, we've taken the interface reference here not the DemoBean class' reference. By doing so, the identity of the DemoBean class is hided and kept isolated. No one knows the existence of DemoBean class by seeing Client1.java. As a result they don't even know the properties in the DemoBean class. We can access greet() method but not the getter or setter methods of the class as the reference is Demo type. As the method returns java.lang.Object, it is typecasted to Demo.

Now using this reference we can call the greet() method. In this way, you can get started with spring framework easily. This is simple program and i hope that this post have remove any fear (if there) about Spring Framework. That is dead easy.

No comments: