项目启动自动执行方法的几种方式

1.具体类实现InitializingBean接口,实现其afterPropertiesSet()方法;或抽象类实现该接口方法,实例化子类时也会启动afterPropertiesSet()方法。

示例链接
2.实现ApplicationListener接口,实现onApplicationEvent方法;如下示例,程序启动时获取实现LifeCycle接口的类,运行LifeCycle实现类的startup方法和shutdown方法。

/**
 *  组件生命周期管理
 */
@Slf4j
@Component
public class ComponentContainer implements ApplicationListener<ContextRefreshedEvent> {

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		//  get beans of LifeCycle
		Map<String, LifeCycle> components = event.getApplicationContext().getBeansOfType(LifeCycle.class);
		Collection<LifeCycle> instances = toArrayList(components);
		//  startup
		instances.forEach(LifeCycle::startup);
		//  shutdown
		Runtime.getRuntime().addShutdownHook(new Thread(() -> {
			instances.forEach(LifeCycle::shutdown);
		}));
	}
}
posted @ 2020-11-23 17:58  一南瓜子  阅读(281)  评论(0编辑  收藏  举报