Spring – Depends On | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

This image has an empty alt attribute; its file name is image-1.png

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()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s