Search This Blog

Thursday, April 7, 2016

Why Spring framework and What exactly is Spring for?

One of the hardest part in learning Spring is to understand why do you need spring and what is it exactly. Once this is clear, rest all becomes easy. Spring is generally described as ” A light weight framework for building Java applications”. This means any type of Java application – standalone java, JEE applications , Web applications etc. The light weight means you have to make only a few change or none at all to your application code to get the benefits of Spring. This is very important. You don’t need to extend your classes from any particular Spring framework component to get the framework features. This statement is applicable to Spring core.
Spring provides IOC  ( Inversion of Control) and DI ( Dependency Injection ) Capabilities. Minimizing the Dependencies is one of most important factors in creating maintainable, extensible software and Spring solves this beautifully. Let us explore IOC and Dependency Injection in the next section.

Inversion of Control ( IOC )

IoC is a technique that externalizes the creation and management of component dependencies. Inversion of Control is best understood through the term the “Hollywood Principle,” which basically means “Don’t call me, I’ll call you.” 
Consider the case where  Class Person depends on an instance of Class Address.  In traditional programming practice, Class Person either instantiates an instance of Address or Class Person uses a factory class to get the instance of Address. With the IOC practice, an instance of Address is given to Person at run time by the framework.  Thus the dependency is injected by the framework at run time and hence it is also called Dependency Injection. Effectively Inversion of Control is a means to achieve Dependency Injection. Many people use IOC and Dependency Injection interchangeably. In fact Spring acts like a container providing your application classes with all dependencies it needs.
Let us explore the beauty of Dependency Injection with an example
 package com.javahash.spring;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

class Person {

Address address;

public Person() {

}

@Autowired

public void setAddress(Address a){

this.address=a;

}

public Address getAddress(){

return address;

}

}

In the above Code, we simply tell spring that Person requires an instance of Address and that dependency should be satisfied using the setter method annotated with @Autowire.
@Autowired will instruct Spring framework to look for a bean that implements the required interface and inject it automatically via the setter.
The spring framework will  instantiate a valid instance of Address and wire it to the Person class. This is the beauty of Dependency Injection / IOC. There is no plumbing code put by the developer to satisfy the dependency. In my opinion IOC/ DI is the most important reason for the popularity and usefulness of Spring framework.  Spring framework provides better means of  non intrusive, plug-gable programming model.
There is more to Spring – it also provides declarative programming with AOP ( Aspect Oriented Programming). This is a better way to implement cross cutting concerns without the needs to use plumbing code all over the core business classes.
AOP enables you to think about concerns or aspects in your system. Typical concerns are transaction management, logging etc. AOP enables you to capture the cross-cutting code in modules such as interceptors that can be applied declaratively wherever the concern they express applies.Spring includes a proxy-based AOP framework.
But is that all that Spring offers ?. The answer is a BIG NO. Spring provides a lot of components that help with data access / integration, Web programming and other common programming requirements.
spring-overview
Spring also has a number of projects than utilizes the spring core and makes programming easier and cleaner.  Few of the Spring projects are
  • Spring Batch
  • Spring AMQP
  • Spring Boot
  • Spring Data Commons
  • Spring Data GemFire
  • Spring Data JDBC Extensions
  • Spring Data JDBC Extensions
  • Spring Data JPA
  • Spring Data MongoDB
  • Spring Data Neo4J
  • Spring Data Redis
  • Spring Data REST
  • Spring Data Solr
  • Spring Flex
  • Spring for Android
  • Spring for Apache Hadoop
  • Spring Framework
  • Spring HATEOAS
  • Spring Integration
  • Spring LDAP
  • Spring Mobile
  • Spring Roo
  • Spring Security
  • Spring Security OAuth
  • Spring Shell
  • Spring Social
  • Spring Social Facebook
  • Spring Social Twitter
  • Spring Web Flow
  • Spring Web Services


Basically Spring is a framework for  which is a pattern that allows to build very decoupled systems. I'll try to explain you the simplest I can (this isn't a short answer).

The problem

For example, suppose you need to list the users of the system and thus declare an interface called UserLister:
public interface UserLister {
    List getUsers();
}
And maybe an implementation accessing a database to get all the users:
public class UserListerDB implements UserLister {
    public List getUsers() {
        // DB access code here
    }
}
In your view you'll need to access an instance (just an example, remember):
public class SomeView {
    private UserLister userLister;

    public void render() {
        List users = userLister.getUsers();
        view.render(users);
    }
}
Note that the code above doesn't have initialized the variable userLister. What should we do? If I explicitly instantiate the object like this:
UserLister userLister = new UserListerDB();
...I'd couple the view with my implementation of the class that access the DB. What if I want to switch from the DB implementation to another that gets the user list from a comma-separated file (remember, it's an example)? In that case I would go to my code again and change the last line by:
UserLister userLister = new UserListerCommaSeparatedFile();
This has no problem with a small program like this but... What happens in a program that has hundreds of views and a similar number of business classes. The maintenance becomes a nightmare!

Spring (Dependency Injection) approach

What Spring does is to wire the classes up by using a XML file, this way all the objects are instantiated and initialized by Spring and injected in the right places (Servlets, Web Frameworks, Business classes, DAOs, etc, etc, etc...).
Going back to the example in Spring we just need to have a setter for the userLister field and have an XML like this:



    

This way when the view is created it magically will have a UserLister ready to work.
List users = userLister.getUsers();  // This will actually work
                                           // without adding any line of code
It is great! Isn't it?
  • What if you want to use another implementation of your UserLister interface? Just change the XML
  • What if don't have a UserLister implementation ready? Program a temporal mock implementation of UserLister and ease the development of the view
  • What if I don't want to use Spring anymore? Just don't use it! Your application isn't coupled to it. Inversion of Control states: "The application controls the framework, not the framework controls the application".
There are some other options for Dependency Injection around there, what in my opinion has made Spring so famous besides its simplicity, elegance and stability is that the guys of SpringSource have programmed many many POJOs that help to integrate Spring with many other common frameworks without being intrusive in your application. Also Spring has several good subprojects like Spring MVC, Spring WebFlow, Spring Security and again a loooong list of etceteras.

No comments:

My Profile

My photo
can be reached at 09916017317