当spring 容器初始化完成后执行某个方法

package com.yk.test.executor.processor;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class InstantiationTracingBeanPostProcessor implements ApplicationListener {

	public void onApplicationEvent(ContextRefreshedEvent event) {
		if (event.getApplicationContext().getParent() == null) {// root
			System.out.println("=====================================");
			System.out.println("============spring 初始化完成===========");
			System.out.println("============spring 初始化完成===========");
			System.out.println("=====================================");
		}
	}
	
}

application.xml配置(spring3.1)




	
	
	
	  
	
	
	
	
		
		
		
	



注解方式

import org.apache.log4j.Logger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class InstantiationTracingBeanPostProcessor implements ApplicationListener {

	private static Logger logger =Logger.getLogger(InstantiationTracingBeanPostProcessor.class);
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		//if (event.getApplicationContext().getParent() == null) {// root
			try {
				logger.info("★★★★★★★★★★★★★★★★★★★★★★★★★★★");
				logger.info("============quartz 初始化完成===========");
				logger.info("★★★★★★★★★★★★★★★★★★★★★★★★★★★");
				Scheduler scheduler = new StdSchedulerFactory().getScheduler();
				scheduler.start();
			} catch (SchedulerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		//}
		
	}
	
}


单元测试时,初始化spring容器,阻塞进程结束,测试定时任务

@Test
public void initSpirng(){
	int num = -1;
	System.out.print("Please input a number:");
	Scanner sc = new Scanner((System.in));  //键盘输入
	num = sc.nextInt();
	System.err.println(num);
}
定时任务

@Scheduled(cron="0/5 * *  * * ? ")   //每5秒执行一次
public void myTest(){
	System.out.println("...spring容器不关闭,这样子就可以看定时任务效果...");
}


你可能感兴趣的:(Spring,java)