有时候在创建某个Bean之前,需要先创建另一个Bean,这时可以使用depends-on属性。
public class Shared { private static String value; public static String getValue() { return value; } public static void setValue(String value) { Shared.value = value; } } public class User { public User() { System.out.println("User initialized"); Shared.setValue("Set value in User Constructor!"); } } public class Goods { public Goods() { System.out.println("Goods initialized"); } public String toString() { return "Shared.getValue() = " + Shared.getValue(); } } <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="user" class="User"/> <bean id="goods" class="Goods"/> </beans> //测试 public static void main(String[] args) { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("beans-config.xml")); Goods goods = (Goods)beanFactory.getBean("goods"); System.out.println(goods); } /**Output: Goods initialized Shared.getValue() = null */ 从输出看到,Shared.value属性没有赋值,而给Shared.value属性赋值需要实例化User类,所以我们实例化Goods之前要先实例化User。 修改bean定义文件 <bean id="goods" class="Goods" depends-on="user"/> 再次运行测试 /**Output: User initialized Goods initialized Shared.getValue() = Set value in User Constructor! */ 可以看到,在实例化Goods之前先实例化了User。
但是我运行上面 加不加depends on 都是先实例化了。。
有个评论解决了我的疑惑:
实测通过ApplicationContext ac = new ClassPathXmlApplicationContext("depends_on.xml");
方式加载bean,和通过XmlBeanFactory 效果不同,通过ApplicationContext 默认所有的bean都是非赖加载,而通过XmlBeanFactory 都是懒加载的,所以在ApplicationContext 容器中不管是否设置依赖关系通过最后的得出结果都是一致的
转自:http://chenfeng0104.iteye.com/blog/757875