Home  >  Spring Core

Example of @DependsOn in Spring

By Arvind Rai, March 25, 2013
@DependsOn in spring is used with @Configuration. @DependsOn sets bean that container will initialize one bean after given bean. IoC guarantees that depending bean will be created before the bean which depends on this bean. We can also achieve the same using XML application context. Find the link.

Java Configuration with @DependsOn

AppConfig.java
package com.concretepage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
@Configuration
public class AppConfig  {
	@Bean(name="college")
	public College getCollege(){
		College c= new College();
		c.setLocation("Varanasi");
		c.setName("UP College");
		return c;
	}
	@Bean(name="student")
	@DependsOn("college")
	public Student getStudent(){
		Student s= new Student();
		s.setName("Ram");
		s.setCollege(getCollege());
		return s;
	}
} 

Create Beans

Student.java
package com.concretepage;
public class Student {
	private String name;
	private College college;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public College getCollege() {
		return college;
	}
	public void setCollege(College college) {
		this.college = college;
	}
	
} 
College.java
package com.concretepage;
public class College {
	private String name;
	private String location;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
} 

Run Application

AppTest.java
package com.concretepage;
import java.sql.SQLException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AppTest {
	public static void main(String[] args) throws SQLException {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
 		ctx.register(AppConfig.class);
		ctx.refresh();
		Student st= (Student)ctx.getBean("student");
	        System.out.println(st.getCollege().getName());		
	}
}  
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us