博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring bean depends on
阅读量:4594 次
发布时间:2019-06-09

本文共 1787 字,大约阅读时间需要 5 分钟。

有时候在创建某个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

转载于:https://www.cnblogs.com/smile0120/p/5190364.html

你可能感兴趣的文章
loj10035. 「一本通 2.1 练习 1」Power Strings
查看>>
%s的用法
查看>>
调用底层不能直接访问的类和方法
查看>>
清理缓存的方法 #DF
查看>>
JAVA array,map 转 json 字符串
查看>>
2017-12-27练习
查看>>
NET设计规范(二) 命名规范
查看>>
VMware 9.0.1安装Mac OS X Mountain Lion 10.8.2
查看>>
SSL延迟
查看>>
android新手关于左右滑动的问题,布局把<android.support.v4.view.ViewPager/><ImageView/> 放在上面就不行了。...
查看>>
深入理解DIP、IoC、DI以及IoC容器
查看>>
赋值文件
查看>>
Vue 数组 字典 template v-for 的使用
查看>>
蓝牙模块选择经验谈
查看>>
java中==和equals
查看>>
CCActionPageTurn3D
查看>>
python random
查看>>
esp32-智能语音-cli(调试交互命令)
查看>>
netty与MQ使用心得
查看>>
关于dl dt dd 文字过长换行在移动端显示对齐的探讨总结
查看>>