Friday, August 16, 2013

JAVA Spring Tutorial-DI (Dependency Injection) and AOP (Aspect Oriented Programming)

Spring Basic Concepts


This post talks about JAVA Spring Dependency Injection and AOP. Its a small Spring Tutorial to learn the basic Spring Concepts.

What is Spring?

Spring is an open source framework. Spring was created to address the complexity of enterprise application development, and makes it possible to use plain-vanilla JavaBeans to achieve things that were previously only possible with EJBs. But Spring’s usefulness isn’t limited to server-side development. Any Java application can benefit from Spring in terms of simplicity, testability, and loose coupling.

Spring simplifies Java development. That’s a bold statement! Many JAVA frameworks claim and also do simplify the development. But how does Spring is doing it?

Spring does it by using four key strategies:

 Lightweight and minimally invasive development with plain old Java objects
   (POJOs)
 Loose coupling through dependency injection(DI) and interface orientation
 Declarative programming through aspects and common conventions (AOP)

Boilerplate reduction through aspects and templates

Let us take a closer look at each of the above strategies:



1. Unleashing the power of POJOs:


Some frameworks compelled you to extend, implement or even sometimes write methods in your program which are unnecessary from a programmers point of view. For Example in EJB 2.0 users need to include ejbActivate(), ejbPassivate() methods necessarily. 

Spring avoids (as much as possible) littering your application code with its API.

Spring almost never forces you to implement a Spring-specific interface or extend a

Spring-specific class. Instead, the classes in a Spring-based application often have no

indication that they’re being used by Spring. At worst, a class may be annotated with

one of Spring’s annotations, but is otherwise a POJO.


To illustrate, consider a small example HelloWorldBean class shown below:

package com.habuma.spring;
public classHelloWorldBean
{
   public StringsayHello()
   {
       return"HelloWorld";
   }
}

Isnt this as simple as core JAVA, without the code being littered by any lifecycle methods, no implements, no extends and moreover no imports from Spring. 

NOTE: 
Despite their simple form, POJOs can be powerful. One of the ways Spring empowers POJOs is by assembling them using dependency injection. Let’s see how dependency injection can help keep application objects decoupled from each other.


2. Dependency Injection (DI): 


Any nontrivial application (pretty much anything more complex than a Hello World example) is made up of two or more classes that collaborate with each other to perform some business logic. 

Traditionally, each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies). This can lead to highly coupled and hard-to-test code. For more on what is coupling refer here.


Coupling is a two-headed beast. On one hand, tightly coupled code is difficult to test, difficult to reuse, difficult to understand, and typically exhibits “whack-a-mole” bug behavior (fixing one bug results in the creation of one or more new bugs). On the other hand, a certain amount of coupling is necessary—completely uncoupled code doesn’t do anything. In order to do anything useful, classes need to know about each other somehow. Coupling is necessary, but should be carefully managed.

NOTE:
With Dependency Injection, on the other hand, objects are given their dependencies at creation time by some third party that coordinates each object in the system. **Objects aren’t expected to create or obtain their dependencies—dependencies are injected into the objects that need them**.

**That’s the key benefit of DI—loose coupling**. If an object only knows about its dependencies by their interface (not by their implementation or how they’re instantiated), then the dependency can be swapped out with a different implementation without the depending object knowing the difference.





DI follows the behaviour as shown in the figure. As opposed to Foo having required to acquire its dependencies on its own, DI involves giving of the dependencies to Foo.

All of this is done by simple configuration file used in Spring called application context.

Example:

Consider a BraveKnight who performs some quest:

public classBraveKnightimplementsKnight{
privateQuestquest;
public BraveKnight(Questquest)
{
    this.quest=quest;
}
public voidembarkOnQuest()throwsQuestException
{
    quest.embark();
}
}

BraveKnight doesn’t create his ownquest. Instead, he’s given a quest at construction time as a constructor argument. This is a type of dependency injection known as constructor injection. What’s more, the quest he’s given is typed as Quest, an interface that all quests
implement. So BraveKnight could embark on a RescueDamselQuest, a SlayDragonQuest, a MakeRoundTableRounderQuest, or any other Quest implementation he’s given.

The point here is that BraveKnight isn’t coupled to any specific implementation of
Quest. It doesn’t matter to him what kind of quest he’s asked to embark upon, so long
as it implements the Quest interface. That’s the key benefit of DI—loose coupling. If
an object only knows about its dependencies by their interface (not by their implemen-
tation or how they’re instantiated), then the dependency can be swapped out with a
different implementation without the depending object knowing the difference.

INJECTING A QUEST INTO A KNIGHT

Now that your BraveKnight class is written in such a way that you can give him any quest you want, how can you specify which Quest to give him? 

The act of creating associations between application components is commonly referred to as wiring. In Spring, there are many ways to wire components together, but a common
approach has always been via XML. The following listing shows a simple Spring config-
uration file, knights.xml, that gives a BraveKnight a SlayDragonQuest.


<?xml version="1.0"encoding="UTF-8"?>
<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="knight"class="com.springinaction.knights.BraveKnight">
<constructor-argref="quest"/>
</bean>
<bean id="quest"
class="com.springinaction.knights.SlayDragonQuest"/>
</beans>

As we see a "quest"  is injected to a knight. Now if you want to give a knight some other quest, then you just need to add on more bean in the above config file without affecting your JAVA code implementation.


In a Spring application, an application context loads bean definitions and wires them together. The Spring application context is fully responsible for the creation of and wiring of the objects that make up the application. Spring comes with several implementations of its application context, each primarily differing only in how they load their configuration.


3. Aspect Oriented Programming (AOP):


AOP is a good example of Declarative programming which I covered in my earlier post.

Although DI makes it possible to tie software components together loosely, aspect oriented programming enables you to capture functionality that’s used throughout your application in reusable components.

AOP is often defined as a technique that promotes separation of concerns within a software system. Systems are composed of several components, each responsible for a specific piece of functionality. Often these components also carry additional responsibility beyond their core functionality. System services such as logging, transaction management, and security often find their way into components whose core responsibility is something else. These system services are commonly referred to as cross-cutting concerns because they tend to cut across multiple components in a system.

AOP makes it possible to modularize these services and then apply them declaratively to the components that they should affect. This results in components that are more cohesive (For more on cohesion see here) and that focus on their own specific concerns, completely ignorant of any system services that may be involved. In short, aspects ensure that POJOs remain plain.

To illustrate this refer images below:

Without AOP:

As you can see logging, transaction and security related code is often scattered system wide across modules which makes the code less modular.

With AOP:


With AOP, common concerns like Logging, Transaction and Security forms a blanket to the components that they impact. 

This is a powerful concept, as it keeps the cross cutting concerns from littering the application’s core business logic.

Consider in our Knight example that a Knight has a Minstrel which sings on the successful completion of a quest by the Knight.

package com.springinaction.knights;
public classMinstrel{
public voidsingBeforeQuest()
{
    System.out.println("Falala;Theknightissobrave!");
}
public voidsingAfterQuest()
{
    System.out.println("Tee heehe;Thebraveknightdidembarkonaquest!");
}
}

Now without AOP:


package com.springinaction.knights;
public classBraveKnightimplementsKnight{
privateQuestquest;
privateMinstrelminstrel;
public BraveKnight(Questquest,Minstrelminstrel)
{
    this.quest=quest;
    this.minstrel=minstrel;
}
public voidembarkOnQuest()throwsQuestException
{
    minstrel.singBeforeQuest();
    quest.embark();
    minstrel.singAfterQuest();
}
}

The above code should work correctly. But if you note, the Knight each time has to remind Minstrel to do its job. Now is it Knight's business to remind Minstrel each time. According to me she itself should perorm the task that is assigned to her.

Now with AOP we declare Minstrel as an Aspect:


<?xml version="1.0"encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<bean id="knight"class="com.springinaction.knights.BraveKnight">
<constructor-argref="quest"/>
</bean>

<bean id="quest"
class="com.springinaction.knights.SlayDragonQuest"/>

<bean id="minstrel"
class="com.springinaction.knights.Minstrel"/>

<aop:config>
<aop:aspectref="minstrel">
<aop:pointcutid="embark" expression="execution(* *.embarkOnQuest(..))"/>
<aop:beforepointcut-ref="embark" method="singBeforeQuest"/>
<aop:afterpointcut-ref="embark" method="singAfterQuest"/>
</aop:aspect>
</aop:config>

</beans>


Two important points to NOTE:

First, Minstrel is still a POJO—nothing about it indicates that it’s to be used as an aspect. Instead Minstrel became an aspect when we declared it as such in the Spring context.

Second, and most important, Minstrel can be applied to the BraveKnight without the BraveKnight needing to explicitly call on it

In fact, BraveKnight remains completely unaware of the Minstrel’s existence. I should also point out that although you used some Spring magic to turn Minstrel into an aspect, it was declared as a Spring <bean> first. The point here is that you can do anything with Spring aspects that you can do with other Spring beans, such as injecting them with dependencies.


4. Eliminating Boilerplate Code:



Boilerplate code—the code that you often have to write over and over again to accomplish common and otherwise simple tasks.

Spring seeks to eliminate boilerplate code by encapsulating it in templates.

For Example: The JDBC code is written over and over again whenever you want to execute any db query.

To avoid this in Spring there is template for JDBC named jdbcTemplate.

Conclusion:

As listed above Spring simplifies much of your tasks and lets developers to concentrate more on the core business logic.

For more on the above topics with more examples refer Spring In Action 3rd Edition by Craig Walls.

Give in your feedbacks and queries in the comments section below.

No comments:

Post a Comment