This example shows how to use the dependsOn attribute for loading the depended beans referenced by another bean. dependsOn is a attribute as part of the bean tag and it takes the comma separated bean names which are loaded before the actual bean is instantiated. Lets look at the syntax for using the dependsOn attribute.
<bean id="initialize" class="javabeat.net.spring.core.Initialize" depends-on="country"/>
In the above declaration, Initialize bean has the dependency of bean “country” which needs to be loaded. In practical, the initialize bean would want to use some of the resources or data in the Country bean which can be accessed only if that bean has been initialized.
This example shows a simple standalone spring application using dependsOn attribute for loading the beans.
1. Spring Beans
Initialize.java
package javabeat.net.spring.core; public class Initialize { public Initialize() { System.out.println("Initialize Bean Creation : Initializing Values"); } }
Country.java
package javabeat.net.spring.core; public class Country { public Country() { System.out.println("Country Bean Creation : Initializing Country Details..."); } private String countryName; private String countryCode; public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } }
2. Spring Configurations
spring-application-context.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:websocket="http://www.springframework.org/schema/websocket" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd"> <bean id="initialize" class="javabeat.net.spring.core.Initialize" depends-on="country"/> <bean id="country" class="javabeat.net.spring.core.Country" /> </beans>
3. DependsOn Attribute Application Example
SpringStandAloneExample.java
package javabeat.net.spring.core; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringStandAloneExample { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "javabeat\\net\\spring\\core\\spring-application-context.xml"); } }
4. Output
Output…
Country Bean Creation : Initializing Country Details... Initialize Bean Creation : Initializing Values[wpdm_file id=83]