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);
}));
}
}