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.


1 comment: