Spring @DependsOn

Spring allow you specified the bean create order by using @DependsOn orĀ depends-on attribute in xml.

Let’s say we have the follow class:

HighPriorityObject

public class HighPriorityObject {
	
	public HighPriorityObject() {
		System.out.println("HighPriorityObject created");
	}

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}

LowPriorityObject

public class LowPriorityObject {
	
	public LowPriorityObject() {
		System.out.println("LowPriorityObject created");
	}

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

Main Class

@Configuration
public class Main {
	
	@Bean 
	public LowPriorityObject lowPriorityObject(){
		LowPriorityObject object = new LowPriorityObject();
		return object;
	}
	
	@Bean 
	public HighPriorityObject highPriorityObject(){
		HighPriorityObject object = new HighPriorityObject();
		return object;
	}
	
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Main.class);
	}
}

Result 1

As you can see the sequence of creation shown in console is :

LowPriorityObject created
HighPriorityObject created

Modified Main Class

@Configuration
public class Main {

	@Bean 
	@DependsOn("highPriorityObject")
	public LowPriorityObject lowPriorityObject(){
		LowPriorityObject object = new LowPriorityObject();
		return object;
	}
	
	@Bean 
	public HighPriorityObject highPriorityObject(){
		HighPriorityObject object = new HighPriorityObject();
		return object;
	}
	
	
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Main.class);
	}
}

Result 2

HighPriorityObject created
LowPriorityObject created

If you have any specific use case that require you pay attention of the bean creation order, this is a solution that can be consider.

XML-Config

<bean id="highPriorityObject" class="com.xx.HighPriorityObject"/>
	
<bean id="lowPriorityObject" class="com.xx.LowPriorityObject" depends-on="highPriorityObject"/>
Spring @DependsOn

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.