Pages

Sunday, July 7, 2013

The Four Pearls of Spring-2

From the previous post we know spring makes development a kids play and POJO is as awesome as its name.Second of the four strategies which make it super awesome will be looked at in the post.

Pearl 2: D.I.
Ok, so POJO was good but that is what every java class creates objects. We need more to show coolness of Spring. Now, when I say the coolness of spring is that it follows Inversion of Control Design pattern and more specifically it has dependency injection, you can accuse me of being a man of big words and no meaning. So lets first see what is DI aka dependency injection.

Dependency Injection: 

So when we create an application it has usually more than one classes that collaborate with each other to do things. So now when we create object of one class(say A) which needs help of another class(say B) we create an object of B and pass its reference to object of A. This leads to hard coupling and makes it harder to test!! Ok another jargon!! Hard coupling is when two objects are stuck together and can't do things without each other and cant be like mohammed ali(that is float like a butterfly and sting like a bee). Lets take an example.

package com.perius.spring;

public class MohammedAli implements Boxer{

private Butterfly butterfly;
private Bee bee;

public MohammedAli(){

butterfly=new FastButterfly();
bee = new StingingBee();

}

public void fight()[

butterfly.float();
bee.sting();

}
}

Just for the sake of the code the boxer interface


package com.perius.spring;

public interface Boxer{

public void fight();
}


Now when we create a mohammed ali object the constructor will get called and it gets its butterfly and bee to float and sting respectively. So we see that mohammed ali has become tightly coupled to FastButterFly and StingingBee.

Now lets say the boxing coach has come up with new technique and now you have SuperFastButterFly floating technique and a KillerStingingBee stinging technique which just knocks your opponent out. Poor MohammedAli can't get any of those even when he has interfaces Bee and butterfly because he is tightly coupled to FastButterFly and StingingBee objects. And thus JOE has won it.

Basically our MohammedAli class is difficult to test and reuse and understand too and if a bug is introduced in StingingBee it will come to MohammedAli too and there ain't anything you can do about it. 

So now lets look at JoeFrazier who uses dependecy injection


package com.perius.spring;

public class JoeFrazier implements Boxer{

private Butterfly butterfly;
private Bee bee;

public JoeFrazier(Butterfly butterfly,Bee bee){

this.butterfly=butterfly;
this.bee = bee;

}

public void fight()[

butterfly.float();
bee.sting();

}
}


What we have done with Joe is that we have made him loosely coupled. So when Joe gets constructed he gets the butterfly and bee injected to its object at runtime from a third party (may be by his coach :P). So he can get the latest buttterfly floating technique and the latest stinging bee technique.

This is what the spring provides a dependency injection. So when you create beans in such a way that you can give it any object it needs (Alway program to the interfaces!!!!!) spring provides way of creating these runtime associations. This is called wiring. There are many ways to create these wirings but the most ancient of them is via XML lets name it boxer.xml



<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<bean id="joe" class="com.perius.spring.JoeFrazier">
            <contructor-arg ref="butterfly"/>
            <contructor-arg ref="bee"/>
       </bean>


<bean id="butterfly" class="com.perius.spring.SuperFloatingButterfly">
           
       </bean> 


<bean id="bee" class="com.perius.spring.SuperStingingBee">
           
       </bean> 
</beans>


There are a lot of other things in wiring. This is just introduction.

Now how do we use it.The application context loads the bean definition in boxer.xml and wires them together. The spring application context is fully responsible for creation and wiring of objects so you dont need to worry. There are different implementations of application context each differing in how and from where is it loading the bean definition. ClassPathXmlApplicationContext is one such implementation which searches the bean definition in the classpath of the application and loads the beans.

Ex:

package com.perius.spring;

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



public class Ring{


public static void main(String[] args){

   ApplicationContext context = new ClassPathXmlApplicationContext("boxer.xml");

  Boxer boxer=(Boxer) context.getBean("joe");
 joe.fight();

}

Voila! You have a fight!!

The Four Pearls of Spring-1

From the previous post we know spring makes development a kids play.One of  the four strategies which make it do so will be looked at in the post.

Pearl 1: POJO
With an awesome acronym like that you are bound to do awesome things. So, the awesome thing that POJO does is, it does barely anything, other than what you really want it to do!! Now that to you would seem odd. Let me show you a POJO in EJB2.0 first

package com.perius.ejb.session;

import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

public class HelloWorldBean implements SessionBean{

public void ejbActivate()
{

}

public void ejbPassivate()
{

{

public void ejbRemove()
{

}
//couple of more such interface methods to implement which I wont here..

public String sayHello()
{
 return "Hello World!!";
}

}

This is a Bean in EJB2.0 which only has the only function of returning the string "Hello World" everytime it is created and sayHello method is invoked. But we had to implement 4 more methods which would let the bean to hook to the session bean lifecycle . This is forceful requirement. Even I as developer who doesn't want to write all those stupid methods which have nothing to do with my real business logic(Saying hello world) would have to implement them. This is dictatorship!! I hate it. It is like I made a mistake choosing EJB2 for it doesnt work for me. I work for it!

Now our darling Spring avoids this stupid mess by never making me implement spring specific interfaces or extend spring specific classes.(In new spring you have annotations, but still my java code remains) So my beautiful little bean can be used anywhere as it is not bound to spring by any method or interface making it reusable and don't we developers love that!!

So my spring code for the same hellobean would look somewhat like this:

package com.perius.spring;

public class HelloWorldBean(

public String sayHello()
{
    return "Hello World";
}

And shouldn't my bean look like that a plain old java object aka the POJO!!

Introduction to Spring

What is a Java?
Java is a programming language with a unique(almost) ability to run everywhere. It can run on any machine which has a Java Virtual Machine.

What are the major uses of Java?
Java can be used and is used for wide ranging applications from nornal desktop software, web software, games, OS(ex android). Large section of the applications developed are enterprise applications i.e. applications used by big enterprises at a huge level.

What is a framework?
An enterprise application has to do a lot of things like
- doing the stuff the enterprise wants it to do. For example, ticketing application for a bus service.
- data management of the user and the ticketing data/
- transaction management of the ticket transaction
To do these things an application
- should be robust i.e. should have minimum bugs
- should have capability to add further functionality
- should be easy to develop even with such tough demanding requirements.
- should be easy to develop for a large team without collaboration issues.
A framework provides the developers with these functionalities. It is like a guideline for development of applications. It includes its own code to do a lot of things like security transaction management etc for the developer, so that the developer can concentrate on the main business logic(ticketing in the example above). It lets developer to create components(short code capsule for a business function) which he can plug into the framework to create an application.

What is EJB framework?
EJB framework is a open source frame work based on JSR(Java specification request) used for development of enterprise application. It is(was till EJB3.0 came) a very heavy framework. A heavy framework implies that it was a strict framework where the developer had to do a lot of work other than writing plain old java objects(POJO). See old EJB2.0 code to understand how many interfaces and methods the developer had to right just to declare a bean(basic class which stores his application logic). Then there were too many types of beans (Session, entity, message) and deployment  descriptors thus bewildering the developer into a maze. The latest EJB3.0 has become a lot lightweight with annotation based POJO programming, still this blog is about Spring!!


What is Spring framework?
Spring framework is a light-weight framework for enterprise application development.It lets the developer to write his favourite POJO code and then by invoking the power of Dependency Injection and aspect oriented programming making it fairly simple for even an idiot like me to become an enterprise application developer.

How does Spring framework help?
As said above it makes development easy. It does so by following strategies:
- Lightweight and minimally invasive development with Plain Old Java Objects(POJOs)
- Loose coupling through dependency injection and interface orientation.
- Declarative programming through aspects and common conventions
- Boilerplate reduction through aspects and templates.

We will go through what these four strategies intend to do in the next blog.