Had been Going through this framework since many days, so just tried consolidating whatever I observed in my own language. Spring works on a very interesting concept
Dependency Injection , A little related to Factory pattern. Here I am putting a little relevance of relation between Spring and factory pattern
Factory pattern :- One object to conrol the creation of and/or access to other objects
Let us see some practical example
public class A implements {
int number;
A( int no ){
this.number = no;
}
public int getNumber(){
return a;
}
}
public class B {
String abc ;
B(String efg){
this.abc = efg;
}
public String getAbc(){
return abc;
}
}
Now some class C needs to use A and B ,
public class C{
A a = new A(1);
B b = new B("Some thing");
}
IF factory pattern is used , it is responsible for all the initializations
and formalities which are required for creating an object
public class ObjFactory{
public static A getA(int input){
return new A(input);
}
public static B getB(String input){
return new B(input);
}
}
code for client class is :-
public class C{
public static void main(String args[]){
int input = 0;
ObjFactory factory = new ObjFactory();
A a = factory.getA(1);
B b = factory.getB("Some String");
}
}
So technically we are centralizing the generation of object , this will reduce our work in sense , any alteration in the way object is generated if needs to be done can be done in factory instead touching client code
Same is the concept of Spring framework
Dependency Injection :- Instead of you declaring the objects , the instances are injected to the client code , DI is achieved in Spring using an xml , called beans.xml , which works for you to instantiate all the beans in your application
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean name="A"
class="examples.spring.A"
singleton="true">
<constructor-arg>
<value>"Smriti"</value>
</constructor-arg>
</bean>
<bean name="B"
class="examples.spring.B"
singleton="true">
<constructor-arg>
<value>12<value>
</constructor-arg>
</bean>
</beans>
In the above xml file we are passing arguments to the constructor with the help of value element which can be used for any java native types , let it be int, long , spring , double etc.
InputStream is = new FileInputStream("src/examples/spring/beans.xml");
BeanFactory factory = new XmlBeanFactory(is);
A a = (A)factory.getBean(10);
int result = a.getNumber();
This is about the basic idea for Spring.
Please pardon me for using very generic examples , those are basic for general understanding only
references :-
http://www.devx.com/Java/Article/21665
http://www.oodesign.com/factory-pattern.html