DependsOn Attribute in Spring Configuration

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="" 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


public class Initialize {
	public Initialize() {
		System.out.println("Initialize Bean Creation : Initializing Values");


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


<beans xmlns=""

	<bean id="initialize" class="" depends-on="country"/>
	<bean id="country" class="" />


3. DependsOn Attribute Application Example


import org.springframework.context.ApplicationContext;

public class SpringStandAloneExample {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(


4. Output


Country Bean Creation : Initializing Country Details...
Initialize Bean Creation : Initializing Values

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!