`
tuhaitao
  • 浏览: 376085 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

跟随Spring一起初始化

阅读更多
    有时候我们在其启动Spring容器的同时希望也初始化一些我们系统内部的参数,或者缓存等等,这时候我们可以实现spring给我们提供的初始化接口:
   
    public interface InitializingBean {
        void afterPropertiesSet() throws Exception;
    }
    


    实现这个接口即可:
   
package com.tuz.test;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;

public class IndexBuilder implements InitializingBean {
	
	private final Logger log = Logger.getLogger(getClass());
	
	//操作线程延时启动的时间,单位为秒
	private int lazyTime = 10;
	
	//可以通过Spring注入,是否建立索引
	private boolean buildIndex = false;
	
	
	private Thread indexThread = new Thread() {
		@Override
		public void run() {
			try {
				Thread.sleep(lazyTime * 1000);
				log.info("begin index...");
				long beginTime = System.currentTimeMillis();
				//这里可以放入具体要执行的方法
				long costTime = System.currentTimeMillis() - beginTime;
				log.info("index finished.");
				log.info("costed " + costTime + " milliseconds");
			} catch (InterruptedException e) {
				log.error("Index failed!", e);
			}
		}
	};
	

	@Override
	public void afterPropertiesSet() throws Exception {
		if (buildIndex) {
			indexThread.setDaemon(true);
			indexThread.setName("Indexer");
			indexThread.start();
		}
	}

        //geters and seters 这里省略了

}
    

    下边是XML配置文件:
   
    <bean id="IndexBuilder" class="com.tuz.test.IndexBuilder" lazy-init="false">
        <property name="buildIndex" value="true" />
        <property name="lazyTime" value="5" />
    </bean>
    

    很简单的只要实现一个接口就能让我们的应用跟随Spring容器一起初始化了.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics