zoukankan      html  css  js  c++  java
  • 项目启动自动执行方法的几种方式

    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);
    		}));
    	}
    }
    
  • 相关阅读:
    java8时间处理
    HttpServletRequest
    Elasticsearch简介
    springCloud-Alibaba--Sentinel
    Nacos集群部署:
    nginx安装配置
    hibernate 嵌套事务
    linux下cmake安装mysql 源码
    linux下中文乱码问题解决
    tomcat quartz 被触发两次
  • 原文地址:https://www.cnblogs.com/bb-ben99/p/14025932.html
Copyright © 2011-2022 走看看