Donate : Link

WordPress Blog : Link

Applications… : Link

Spring Tutorial Index Page: Link

  • If you want to make create Engine object mandatory before create Car class object then you can go through depends-on.
  • Let say we have 3 classes A, B, and C. A depends on B and B depends on C. So we can write xml file like this.
class A {
}
class B {
}
class C {
}
<beans>
<bean id="a" class="A" depends-on="b">
</bean>
<bean id="b" class="B" depends-on="c">
</bean>
<bean id="c" class="C">
</bean>
</beans>
  • Objects will be create based on the order in which they are declated in xml file.
  • If we use depends-on then the object used in depends-on will create first.

Create Java Project

  • Open Eclipse
  • Go to File -> New -> Others… -> Java Project
  • Create DI-DependsOn project
  • Right click on project -> Build Path -> Configure Build Path -> Libraries tab -> Add External JARs
    - commons-logging-X.X.jar
    - spring-beans-X.X.X.jar
    - spring-context-X.X.X.jar
    - spring-core-X.X.X.jar
    - spring-expression-X.X.X.jar
  • * You can find dtd information from spring-beans-X.X.X.jar -> org -> springframework -> beans -> factory -> xml -> spring-beans.dtd (line no 36 & 37)

spring.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="a" class="com.codeFactory.beans.A" depends-on="b" />
<bean id="b" class="com.codeFactory.beans.B" depends-on="c" />

<bean id="c" class="com.codeFactory.beans.C" />
</beans>

A.java

package com.codeFactory.beans;/**
* @author code.factory
*
*/
public class A {
public A() {
System.out.println("A.A()");
}
}

B.java

package com.codeFactory.beans;/**
* @author code.factory
*
*/
public class B {
public B() {
System.out.println("B.B()");
}
}

C.java

package com.codeFactory.beans;/**
* @author code.factory
*
*/
public class C {
public C() {
System.out.println("C.C()");
}
}

Client.java

package com.codeFactory.test;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codeFactory.beans.A;/**
* @author code.factory
*
*/
public class Client {
public static void main(String... args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("com/codeFactory/resources/spring.xml");

A t = (A) context.getBean("a");
}
}

Output:

C.C()
B.B()
A.A()