Spring Framework - Introduction

By : Juned Laliwala www.attuneww.com

Table Of Content ● Spring Framework Introduction ● Comparison Of Java EE and ● Spring Framework ● Spring Modules and Architecture ● Need For Loose Coupling ● Effect of Loose Coupling Spring Framework Introduction

Spring is a lightweight framework. It can be said as framework of frameworks, as it has capability of working with many frameworks like Struts, Hibernate, EJB.Spring is a special framework, what makes it special is, where we can work all modules like front-end, backend etc. When compared to Hibernate (DB related) and Struts (Front End related), which only allow us to work on limited modules unlike spring.

Spring can be said as lightweight, because it do not use OS libraries, Application servers and only needs just Java libraries and JRE to run. For example, AWT needs OS libraries to run so it is heavy weight.

Spring allows us to use “Association”, which needs less resources and unlike “Inheritance” (where everything is inherited whether they are used or not).And we do not need to inherit particular interface or class for its properties.

We just need to associate with the class we are using. We can say Spring is Non-Invasive because of this feature.This is implemented as POJO (plain old java object)class where we just associate, instead of inheriting. Features

Simplicity

Because of its POJO/POJI type of model, and also its non-invasive. It also does not force users to implement unneeded classes or interfaces by which are not going to be used in applications we build.

Testability

In Spring server is not mandatory, unlike Struts and other frameworks, where if any code-change is there we have to restart server to reflect code changes. But in spring we don’t need to do this. It makes code deployment easy.

Loose coupling

Spring has been built to achieve loose coupling, which makes code building easy, and testing, maintenance easier. In simple terms, we tell spring how we want to create, instead of directly creating( Objects and giving values directly ). This is done by configuration files(XMLs) which store dependencies which are injected into Class, when required.

Aspect Oriented Programming (AOP):

One of key components of Spring is Aspect oriented programming (AOP) framework. The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from application's business logic.

There are various common good examples of aspects including logging, declarative transactions, security, and caching etc.

The key unit of modularity in OOP is class, whereas in AOP unit of modularity is aspect. Whereas DI helps you decouple your application objects from each other, AOP helps you decouple cross-cutting concerns from objects that they affect.

The AOP module of Spring Framework provides aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. Comparison Of Java EE and Spring Framework

JavaEE – This is a platform that implements a standardized specifications which are of collection, and they have been implemented by many vendors for compliance purpose.

Spring – This is an open source framework , which is used for application development, and is mainly used for Java and its related technologies.

Advantages Of Java EE: The primary advantage of java EE is standardisation. Because of standardisation, If Java EE specification is followed and is used to deploy into a Java EE container, then our deployment sizes will be minuscule compared to other frameworks because the runtime dependencies are all included in the container. With it supports quick distributed enterprise application development. We can build applications which are complex, quickly based upon platform with its services and .

Disadvantages Of Java EE: The primary disadvantage of JavaEE is also its standardization. Because it’s a committee process the time to respond to industry changes is slow. The committee is composed of various implementers of the specification, and they have a vested interest in not changing to quickly even if it is to meet the demands of the industry. The Java EE7 specification which was released on 2013 and till now only implementor of it is the reference implementation GlassFish.

Spring Framework: The Spring is an open source framework which focusses on building modern Java applications. Spring is built on top of many core JavaEE specification technologies: For e.g. Spring Web MVC is built on top of Java Servlet API.

Spring applications only need a Java Servlet container for any of them to be deployed. The main advantage of spring framework is, it provides an Inversion of Control (IoC) development environment.

The framework is what which decides, at a high-level, the operations-flow for performing a certain task and developer just plugs-in the necessary specifics at any step.

There are 4 key strategies used by spring for development of an enterprise Java application, and it simplifies application development.

1)Spring framework is light weight and It minimally invasive development with POJO. 2)In Spring loose coupling is achieved through and interface based programming. 3)We can also have Declarative programming through aspects and common conventions. 4)Boilerplate code reduction is achieved through aspects and with templates.

Advantages of using a framework

1)Spring comes with existing technologies like logging framework, ORM framework, J2EE and JDK Timers etc, So we don’t need to explicitly integrate them.

2)Spring enables the developers to use POJOs (Plain Old Java Objects) to develop enterprise applications.

3)Spring WEB framework has web MVC framework, which is a credible alternate to web framework.

4)Spring gives us a consistent transaction management interface, with which we can scale up to global transactions (using JTA) and scale down to a local transaction.

5)Spring is modular complete and modular, because it has a layered architecture.

6)Spring can eliminate the creation of factory classes and singleton classes.

7)Spring includes support for business objects management and expose their services to the presentation components, so that desktop applications and web can access same objects. Shortcomings Of javaEE:

As discussed above, It is a standardized way of implementing and defining a technology.

Also, we cannot achieve Inversion of control, and Dependency Injection etc. Which can be achieved through in Spring.

And, as we have seen, Spring is built upon Java EE, and other java related technologies, and it tried to address the shortcomings of respective modules and make them efficient. Spring Modules and Architecture

DAO:-

DAO provides abstract layer for low level task of connection creation, releasing it. And it maintains a hierarchy of exceptions, rather than throwing complex errors from database vendors. It uses AOP to manage transactions. Transactions can be managed programmatically also. AOP:- Aspect Oriented Programming module provides chance for the developers for defining method-interceptors and pointcuts to keep concerns apart. It is made and configured at run time, so compilation step gets skipped. It facilitates declarative transaction management, which can be easier to maintain.

ORM:- Spring although does not provide its own ORM implementation, but offers support for integration with popular ORM tools like Hibernate, iBATIS SQL Maps, JPA etc.

JEE:- JEE can provide support for JMX, JCA, EJB and JMS. JCA (Java EE Connection API) is like JDBC, except where JDBC focusses on database, and JCA focuses on connecting to legacy systems.

WEB:- Spring is equipped with MVC framework which eases developing web applications. It also integrates with most popular MVC frameworks like Struts, Wicket, JSF, etc.)

CORE:- Provides us Dependency Injection (DI) feature which is the core and basic concept of Spring framework. This module has the BeanFactory, which is implementation of Factory Pattern, and creates bean as per configurations provided by developer in XML file. Need For Loose Coupling

Before we understand, loose coupling, we need to see about tight coupling.

Coupling refers to the degree of direct knowledge that one element has of another. we can say an eg: A and B, only B change its behavior only when A change its behavior.

TightCoupling: Tight coupling is when a group of classes are highly dependent on one another. This scenario arises when a class assumes too many responsibilities, or when one concern is spread over many classes rather than having its own class.

TightCoupling Generic Example

public Class A{

B bObj = new B(); bObj.methodOfB();

} Class B{

public methodOfB() {

} }

Class C{

public methodOfC() { } }

Now Consider, we want to change class B Instances from Class A and put Class C Instance there.

Then we need to change all code related to Class B in Class A. This is tight coupling,

Tight Coupling is bad , because flexibility is reduced and code re- is difficult, it impedes testability, it makes changes much more difficult etc.

Tightly Coupled Object is an object, which needs to know something about each other and are usually highly dependent on each other interfaces. If one Object is changed one object in a tightly coupled application often requires changes to a number of other objects. If it is a small application, changes are easily identified and there is less chance to miss anything.

But in case of large applications, we may not always know these inter-dependencies, and by every programmer or chance, we can miss changes and also difficult to maintain.

TightCouplingExample

Car package com.tight.coupling; public class Car {

public void moveVehicle() { System.out.println("Car is moving"); }

}

Traveller package com.tight.coupling; public class Traveller {

public void travellingInVehicle() {

//creating Car Object, accessing Car methods Car car = new Car(); car.moveVehicle();

/*prolem occurs if we want to change vehicle, to bike for example

So we will use interface here to overcome it */ } } TestClass package com.tight.coupling; import com.tight.coupling.*; public class TestClass {

public static void main(String[] args) {

//creating Traveller Object, accessing traveller methods

Traveller traveller = new Traveller(); traveller.travellingInVehicle();

}}

Now traveller wants to change his vehicle, to bike, then the code which has been hard wired into traveller class has to be changed.

So if it is Enterprise application, having thousands of classes it is almost impossible, And very hard to change all of them. So thats why we go to loose Coupling, and Inversion of Control.

Loose Coupling:

If two objects are loosely coupled, they can interact with each other, even though having little knowledge of each other.

Designs which are Loosely coupled allow us to build flexible systems so changes can be handled easily.But each set of loosely coupled objects are not dependent on others.

With Loose coupling as a design goal, we can reduce the interdependencies between system components, with the goal of reducing the risk that changes in one component will require changes in any other component. Loose coupling is like a generic concept intended to increase system flexibility, make it more maintainable, and also make the framework stable.

Loose coupling is achieved through a design which promotes separation of concerns and single-responsibility.A loosely-coupled class can be consumed and tested independently of other (concrete) classes.

Interfaces are a powerful tool to use for decoupling. Classes can communicate through interfaces rather than other concrete classes, and any class can be on the other end of that communication simply by implementing the interface. interface VehicleInterface package com.loose.coupling; public interface VehicleInterface {

//all vehicles inherit these methods and implement them public void startVehicle();

public void accelerateVehicle();

public void stopVehicle();

}

Car package com.loose.coupling; public class Car implements VehicleInterface {

//Inheriting VehivleInterface Methods @Override public void startVehicle() { System.out.println("car is started");

} @Override public void accelerateVehicle() { System.out.println("car is accelerated");

}

@Override public void stopVehicle() { System.out.println("car is stopped");

}}

Bike package com.loose.coupling; public class Bike implements VehicleInterface {

//Inheriting VehivleInterface Methods

@Override public void startVehicle() { System.out.println("Bike is started");

}

@Override public void accelerateVehicle() { System.out.println("Bike is accelerated"); }

@Override public void stopVehicle() { System.out.println("Bike is stopped");

}

}

Traveller package com.loose.coupling;

public class Traveller {

VehicleInterface vehicle;

//injecting respective bean, through xml file and loose coupling is achieved here public VehicleInterface getVehicle() { return vehicle; } public void setVehicle(VehicleInterface vehicle) { this.vehicle = vehicle; }

public void travellerStartsOnVehicle() { vehicle.startVehicle(); }

public void travellerStopsOnVehicle() { vehicle.stopVehicle(); }

}

TestClass package com.loose.coupling;

import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestClass {

public static void main(String[] args) {

ApplicationContext acObj = new ClassPathXmlApplicationContext("Spring.xml");

//Accessing Bean Traveller travellerBean = (Traveller) acObj.getBean("travellerBean");

//Accessing bean methods, but through interface

//so we achieved loose coupling, //we can switch between car and bike, just by modifying xml file

System.out.println(" ==== Bike Bean injected through XML, using interface inheritance====="); System.out.println(" ==== so LOOSE COUPLING is achieved ===="); travellerBean.travellerStartsOnVehicle(); travellerBean.travellerStopsOnVehicle(); } } spring.xml

Output

==== Bike Bean injected through XML, using interface inheritance======so LOOSE COUPLING is achieved ==== Bike is started Bike is stopped Effect of Loose Coupling

So, now if traveller wants to change his vehicle, he did not need to change any of the code in any class.

He just need to change the Xml file. And Spring Container injects the required Object to the Class as it is required.

With just changing some lines in Xml, if this is achieved, imagine if any large application implements this, and they want to to change some entire service layer or dao layer.

It is very easily achieved. CALL : +91 90999 12995

For more Tutorials & Training Videos

Attune World Wide is a one-stop Technology and IT Infrastructure Solutions provider. We support our clients with the complete Open-source Technology Consultation, Integration, Development, Training and Migration services.

We are catering our services to many countries globally including USA, UK, UAE, Australia, Malaysia etc. and empowering multiple Industries like Retail, Finances, Healthcare, Architecture, IT, Banking, FMCG, Education etc.

Get Online Training