Spring-depends on
depends-on用来表示一个bean A的实例化依靠另一个bean B的实例化, 但是A并不需要持有一个B的对象,如果需要的话就不用depends-on。
示例:
步骤一:
public class SystemSettings { public static int SESSION_TIMEOUT = 30; public static int REFRESH_CYCLE = 60; }
步骤二:
package org.hope.spring.bean.dependon; public class SysInit { public SysInit() { System.out.println("SysInit"); //模拟从数据库中加载系统设置信息 SystemSettings.REFRESH_CYCLE = 100; SystemSettings.SESSION_TIMEOUT = 10; } }
步骤三:
package org.hope.spring.bean.dependon; import java.util.Timer; import java.util.TimerTask; public class CacheManager { public CacheManager() { Timer timer = new Timer(); TimerTask cacheTask = new CacheTask(); timer.schedule(cacheTask, 0, SystemSettings.REFRESH_CYCLE * 1000); } public void cycle() { System.out.println("初始值:" + SystemSettings.REFRESH_CYCLE); } }
步骤四:
<bean id="sysInit" class="org.hope.spring.bean.dependon.SysInit"/> <bean id="manager" class="org.hope.spring.bean.dependon.CacheManager" depends-on="sysInit"/>
步骤五:
package org.hope.spring.bean.dependon; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:bean3.xml"}) public class DependOnTest { @Autowired private CacheManager manager; @Test public void test() { manager.cycle(); } }
结果:
初始值:100
结论:
sysInt先去manager实例化。
https://gitee.com/huayicompany/spring-learn/tree/master/spring-bean
参考:
[1] 《精通Spring4.x企业应用开发实战》,电子工业出版社,陈雄华