Showing posts with label Spring Framework. Show all posts
Showing posts with label Spring Framework. Show all posts

Aspect Oriented Programing With Spring

Yesterday I got a requirement, where I need to add logging in more then 500 existing classes :-(

How could I achieve this ??

of course...

I need to open every file and add some code like


log.info("Beware : ");

a bit labours work isn't it ? and you know what ? my boss wants me to complete these writing 2-3 days :-(

He provided me 500 .java files and ask me to write code so when ever an exception occurred that can be logged in log file.


I am very nervous, sad, irritate.. because of these tedious task and seat in to my cubical with unhappy face.


and then a magic happened.


an angle appears in my computer screen wearing green dress and having a feather in her hand, she said,

"Don't worry Ishan ! I am here to rescue you from your Boss !!!"
"You don't need even a day to complete your task, I'll help you with
my magical configuration & reflaction."

"May I know your name please ?"

"Spring !"
"And these is my AOP feather !"

"But you know, I hate to learn so much of theories. :-("
"Hey I am not here to teach you anything okey... I am here to help you, guide you in very simple way my child !"
"Oooo really ??"

"Yes, Baby. So shall we start working now ?"
"Why not my pleasure :-)"

And finnally we come to one class which intecepts all my 500 classes and put the logging stuff dynamically. So what I need is just
one class with few lines of code and few lines of configuration tht's it.

The logging mechanisam for 500 classes is ready.

I note down my experience of AOP with Spring in following lines.


First of all we need a class where we write some logging stuff. let's say
LoggingInterceptor.

LoggingInterceptor.java

"hey, I don't understand anything other then the getStackTrace(Exception ex) method."
"Don't worry ! let me clear everything is this code."

Let's assume that we are using apache's log4j mechanism for logging.
line no. 7 : imported the Logger of apache.
line no. 8 : imported the ThrowsAdvice of Spring's AOP framework.

Spring is having different types of advices but presently we look for ThrowsAdvice only and later work around the other advices like BeforAdvice, AfterReturnAdvice & AroundAdvice.

ThrowsAdvice :

It is a marker interface which says execute this chunk of code if any exceptions occured.

So when an exception is being thrown
afterThrowing(Method method, Object[] args, Object target, Throwable throwable) method is being called. See the segnature of this method.

Here using reflaction your desired chunk of code is being added and ofcourse executed.

"Okey ! but not fully cleared yet. What I understand is that we write some code in a class which we want to implement in all 500 classes. But I am not cleared that how this will executed at runtime ? How the spring will come to know that where to add this
code and where to not ?"

"Just Relax ! We discuss everything..."

line no. 10 : Our LoggingInterceptor implements the ThrowsAdvice and get the power of Spring AOP.
line no. 13 : Provide the implementation of
afterThrowing(Method method, Object[] args, Object target, Throwable throwable) method.

As our problem is to implement the logging stuff in all the service layered implementations (500 classes).
and my packages are like...


com.springtutorial.aop.service.impl
and in side this package all my 500 classes reside.

As we know in spring we need to create the beans. So let we create a bean of our LoggingInterceptor.

application-context.xml

Now the question come that how spring come to know that what and where to do ?

So what we want to spring to do ?
1. find all the classes available under
com.springtutorial.aop.service.impl package only.
2. find the class where we write the Logging stuff.
3. combine both the things at runtime if any exception thrown.

Let's modify our configuration file...
application-context.xml

Please note that
line no
. 4 : we added name space for aop. line no. 7 : added schema location for aop. line no. 11 : Special used a feature provided in 2.x version for aop configuration. line no. 12 : Define a pointcut What is a point cut ? A point cut defines a specific place where you want to add the cross cutting functionalities in our case that is writing logs. the execution attribute of pointcut tag accepts the regex as the arguments. Here we can go upto method level as well but presently we only go up to a package level. line no. 13 : Define a advisor What is an advisor ? An advisor is what brings the advise(LoggingInterceptor) and the pointcut(500 classes) brings together. The spring will create a proxy having functionalities of both the classes at run time.

And nowwwwwwwwww

hey your AOP stuffs has been completed..
let's test it.

We are having one ProblematicServiceImpl which throws a RunTimeException.

ProblematicServiceImpl.java

and we have a main class

TestMain.java

So when we run our TestMain, an ArithmeticException is being thrown by the code and the details of this exception is eing written automatically in our log file using Spring AOP.

Awesome Framework !!!
isn't it ?

It reduces our work a lot, and provide the space to more concentrate on business needs of the applications.

A Simple Spring Tutorial - II

Hi friends,

How are you doing???


gr888...


:-)

Today we are going to dive in some more spring bean attributes and try to implement some design patters..

ummm ummm..

don't worry we are not going to write even a single line of code for implementing design pattern but just request spring to implement that for us...

I heard that so many people impressed by the way you implemented Singleton Pattern. (without writing a single line of code)

But friends are people who always come up with new problems when you complete with one. :-)

And here is our another problem.



"Hey Ishan ! I want to implement factory pattern in our cake project.", "Okey Sir !" "See, I want a Cake Factory that'll construct cakes for us."
"As you please Sir."


So let's start working on Factory Pattern guys...

We have the CakeForest.java as our Cake, now what we need is a Factory...
let's say CakeFactory.java


CakeFactory.java
now we are spring developers, so we wont code in old fashion :-)

we just modify our application-context a bit and implementation of factory pattern is ready....
and our application-context.xml is..........

application-context.xml

This is how we can use factory pattern with spring.

Please notice that we used following attributes here :
  • scope="singleton" : This attribute implements the Singleton Pattern for us.
In our factory bean definition we used following factory related attributes.
  • factory-bean = "factory" : This is the name of the bean of Factory Class.
  • factory-method ="createCake" : This is the name of the method which constructs the objects.
  • Hey this is not the end of story :-) there are much more about factory in Spring.
  • lazy-init="true" : as said earlier this will create the object when it is needed.


If you want to decide in your factory method that you want to create a Pineapple or a BlackForest according to the argument.

These are the updated files for you...


CakeFactory.java

and

application-context.xml

So this way we can very easily and beautifully implement the Factory Pattern in our code.

If you want to implement it more sophisticated way or what your need is something more then Spring's FactoryBean interface is also there for you.


A Simple Spring Tutorial - I

We are having very curiosity about spring that what is it ?
how to use it ?
how it will reduce my code :-) (as being a developer I always think) and because of these questions may be you are reading my blog.

Thank you friends for coming here.

Well Spring is a magic box which is full of :
Container, Web Services, MVC, Webflow etc etc
in short Spring is all a developer needs :-)


Usually being a developer I hate to attend boring lectures and theories but would like to learn the core concepts of course. So rather then diving very deep in all boring theories and big words let's start our learning process.

Core Container
The core container provides fundamental functionality of Spring. It's primary component is the 'BeanFactory' an implementation of the factory pattern. The BeanFactory applies the IoC pattern to separate an application’s configuration & dependency specification from the actual application code. -confused :-( (hey I am not talking about you buddy.)

Rather then getting jumbled myself with this complex definition would prefer to code with my previous style and here is the requirement.

"Develop cake interface which give me a cake, when I ask for it." - You know who can order me like this.

So my classes are :
  • Interface Cake
  • Class BlackForest
  • Class CakeMain
Cake.java
BlackForest.java
CakeMain.java

let's see what is happing when we run the main class :

Our application creates the object(s) of BlackForest in heap and assign it with reference of cake, am i right ?
  • Every time method called, a new object of BlackForest is being created as we don’t implemented the singleton design pattern otherwise the same object would be used.
  • Once a class is complied, and if we want to change the implementation i.e. now I want Pineapple flavoured cake and not the previous BlackForest, we have to rewrite & compile the class for changing the dependency I mean the implementation.
  • It is also an overhead on our application to create the objects for itself by itself.

Container : Hey why are you looking so sad ?
Application : I was born to handle complex business logic, automating systems, calculations etc but for all these I need so many objects of different types and you know I have to prepare these object also :-( there is no one there to help me out.
Container : Oooo So sad !

This was the scenario one.

Now lets try to think differently...
"Oooo one more concept to learn I am happy with my previous one." this is not your feeling right b'coz you are here to learn new things.
  • When you need an object of BlackForest, some one is there with plate, again he is ready to serve you your desired flavour whether BlackForest,Pineapple or anything you want. "Fantastic..."
  • Again you get flexibility to define your dependency outside your classes. I mean just define your reference inside your class and container will deicide according to your instructions to him which object to assign.
  • In addition you get the flexibility to say I want to implement Singleton for this class, I don’t want to implement for that class. I want to create object of this class at class loading and not of that object ;-)
Now lets see how spring core container helps us.... hey wait if you didn't download the spring framework then download it first.
please add the spring.jar in your build path.
now we only need to add is one xml file, this file contains the configuration for beans.

application-contex.xml

Please notice in this xml file in side the beans tag there is a bean tag.
In this bean tag we specified following two properties :
  • id : id is the actual object reference name specified in our class(where we want the object of specified class) in our case this is "cake" which we defined in our main class.
  • class :the full qualified class name in our case that is tutorial1.BlackForest. Please notice that there is no need to give the .java extention.
Please make the following changes in CakeMain

CakeMain.java
We need to note few things about the new Main class

  • We created only the reference of Cake interface.
  • We created an object of ApplicationContext with the help of ClassPathXmlApplicationContext class and passed the name of our xml file to it.
  • Here AppliationContext and ClassPathXmlApplicationContext both are provided by spring framework.
  • Then we call method getBean(String beanId) of ApplicationContext class, return type of this method is Object so we need to cast it to Cake as we know that by passing "cake" it will return a Cake implementation.(Our dependency is getting injected with the help of spring according to
  • configuration provided in xml path)
  • The last print statement will tell us the name of Cake we get.

Can you tell me please now instead of BlackForest I want the new Pineapple, what the changes we need to do ? exactly.... first of all

we need to add new implementation for Peneapple.
Pineapple.java

and we need to change the class name from BlackForest to Pineapple in our application-context.xml, the new xml is
application-context.xml
That means here we are changing implementation i.e dependency but we do not need to change the Main class what we need is a simple configuration.

Thus our application becomes coupled and highly cohesive.

Points to note about Spring Core Container are

  • It creates object for your application, now object creation is no more headache of your application.
  • What you need is a very straight forward configuration(instruction) file having information about dependencies.
  • You can also configure that whether you want to implement Singleton or not, When you want to create the object i.e. at class loading or when it needed.
  • For implementing Singleton just add one attribute session="singleton". By default all beans are singletons so if you don't want to make it singletonthen give the scope according to your need like session, prototype.
  • If you want to lazily load your objects then give lazy-loading="true". By default it is false.
So now the picture is changed,
here objects are created by container and provided to application when & where needed.

Application : Are you joking ? are you really going to create for me?
Spring Container : Yes my friend, don't create object yourself, I'll create them for you.
Application : Thanks a lot dear, now I can utilize my resources in some other complicated business stuffs.
Spring Container : Welcome !


"Hey ishan I recall that you mentioned one word IoC what is that ? You didn't said anything about that." (question arise in your mind right ??? ;-)

Inversion of Control (IoC) and Dependency Injection(DI)
  • As we learnt objects initial state and life cycle are handled by the environment i.e. container and not by the object itself. The code you write must be highly reusable and modular. It must be independent from environment so rather the creating object in side your code, create them outside and load them using setters. This is called IoC.
  • To get the actual object specifically in programming is called the dependency and the process of supply dependency from outside is called DI.
  • So the dependency(object) is being injected in application using IoC in Spring Core Container.

Do some goggling and tell me
what is Hollywood Principle ?

In simple words, The object of particular class is created by container according to the configuration given in the xml file and that(object) will be given to application using setter or constructor when and where required.

This way we can have Setter DI, Constructor DI, Interface DI.
  • Setter DI : injecting the object using setter method.
  • Constructor DI : injecting the object using constructor.
  • Interface DI : proxy of interface is being instantiated.
This is a simple introduction of Spring Core Container, Inversion of Control and Dependency Injection. There is lot more to learn, but with above knowledge we can start our development.

Friends very soon we'll meet again with Object Compositions in spring where we can use above DIes and also with a web application.


Spring is there to satisfy all our needs, lets celebrate with your favourite bear and apple juice of mine ;-) and of course the cake is ready so lets celebrate our first spring program :-)


Thank you,
Ishan Dave