Sunday, July 14, 2013

Spring for Absolute Beginners

Last week I attended to a Spring session at the office (Adroitlogic) and it was the first time I got a sound idea about this framework. So I would like to share what I got from that session and from further readings as a beginner for this popular framework.

Spring enables applications development much easier in JEE where the programmer can concentrate on the business logic rather than on the object creation. As a framework Spring provides Inversion of Control which is one of the main advantage of it. So a clear idea on IOC is helpful in understanding advantages of using Spring. In a normal Java application objects are created by constructors or methods in a class which make that class depends on instantiating objects. In other words methods or constructors have to know about implementation details (constructor arguments etc.) of the other classes. This approach has many disadvantages such as,
  • Difficulty in testing classes independently
  • Re-usability issues as classes highly depend on others
  • Maintenance problems because changes are very difficult as classes are tightly coupled
IOC overcome these problems which keep classes free from creating objects and it can concentrate on the core functionalities just using references. Objects for these references are created and set by the IOC container and this is also known as the Hollywood principle: "Don't call me, I'll call you". Spring framework provide Dependency Injection which is on form of IOC. You will understand this from the following example. I have used intellij idea Ultimate Edition 12 as the IDE for illustrating the example and if you try the example, you will not face a significant difficulty in a different version. Now lets move to the example.

Here I have created a simple java application without the support of Spring framework first. 

Step 1 : Select File -> New Project. You will get the following window.




Select Java Hello World as application type and specify a name for the project and press next. Then do not check any option and press finish. You will get your project structure similar to following.


For this example I have used a simple Car and a Driver classes and Application class which runs the application. 

Step 2 : Use a desired package structure and create those classes as following. 

Car.java


Driver.java


Application.java



To run Application.java right click on it in the project pane and then you will get the desired output. But as I mentioned earlier Car object is instantiated by Driver and Driver by main method. Now let's do it using Spring as a basic example.

As additional libraries make sure your have the followings
  • spring-core-3.2.2.RELEASE
  • spring-beans-3.2.2.RELEASE
  • spring-expression-3.2.2.RELEASE
  • commons-logging-1.1.1
In order to add these as dependencies to your project select 'Open Module Settings' by right clicking on your project. Select 'libraries' and add locate your libraries after selecting the Java as in the figure below.


After adding dependencies next step is to change the driver class. This class does not have to worry about instantiating car object anymore. Change Driver.java as below

Driver.java


Now we have to provide information to the framework about instances that we need to create. There are three ways to do configuration and they are XML, annotation and Java based configuration.  Here I am describing how to configure an XML file. We can use the support provided by the IDE to make our life easier. Right click on the 'src' directory and select 'Spring Config' by New -> XML Configuration File -> Spring Config. Name it as Beans.xml. If this is not available in your environment create a bare XML file and insert 'beans' tag pair with the attributes,
  • xmlns="http://www.springframework.org/schema/beans" 
  • xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  and
  • xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
beans tag is the root tag for spring configuration file. We can define instance details within that using 'bean' tag. Available tags and attributes will be discussed later and your XML configuration should be something like this. 

Beans.xml

Together with this change your main method as below.

Application.java


This reads the Beans.xml and creates the spring's Application context which contains beans defined in the XML. These beans can be retrieved by their IDs and then cast into their types. ClassPathXmlApplicationContext find the xml in the class path which is src directory in this case. If you use FileSystemXmlApplicationContext you have to specify the absolute path of the file as 
file:/home/samila/learn/spring/src/Beans.xml for example. 

Congratulations. You have written your first spring application. Now it is time to run the application and verify the correctness. Run the Application.java as mentioned earlier and you will observe the same output. You can now inject any object that implements Vehicle interface via xml beans easily without changing the code which makes the application highly maintainable.

Now it is time to get to know some useful XML tags in spring configuration files.
  • beans - unique root tag of the configuration
  • bean - used to describe a bean with a unique value for 'id' or 'name' attribute. 
  • constructor-arg - this tag is used within bean tag to define values for constructor arguments. You can use self explanatory name, value, type attributes and 'ref' if you refer to an already defined bean. In this case provide the identifier of the referred bean as the value. You may use more than one constructor-arg tag within one bean tag depending on the constructor of the bean.
  • property tags are used within bean definition to define a values for attributes of the bean. name, value and ref attributes can be used.
These are some commonly used spring configurations tags and 'scope' is used as an attribute for bean tag for which allowed values are singleton, prototype, request, session, global-session. You can use this optional attribute depending on the requirement and if you do not specify scope explicitly it's scope is considered to be singleton. You can find more about scope here.

I have used very basic features of Spring framework and there are lot more to learn including bean lazy initialization and specifying properties such as lists, maps. But you can easily grab those areas after understanding the basic concept.  

                         http://www.tutorialspoint.com/spring/
                         http://www.slideshare.net/analizator   

Thanks.

No comments:

Post a Comment