1.Bean初始化后执行

使用 spring 提供的 @PostConstruct 和 @PreDestroy 注解来实现对象实例的启动和销毁时要执行的代码。

package com.dada.test.config;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @Description:
 * @author: ztd
 * @date 2019/4/25 下午7:35
 */
@Component
public class BeanInitDestory {
    @PostConstruct
    public void init() {
        System.out.println("bean初始化之后执行...");
    }

    @PreDestroy
    public void destory() {
        System.out.println("bean销毁之后执行...");
    }
}

2.Spring容器启动后执行

使用Spring提供的ApplicationRunner接口来实现容器启动后执行特定代码逻辑。

package com.dada.test.config;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * spring 容器启动之后执行方法
 * @author: ztd
 * @date 2019/4/25 下午7:00
 */
@Component
public class SpringStarter implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("spring启动后执行方法...");
    }
}

3.Spring 容器各个事件的回调

通过实现ApplicationListener的接口来获取Spring在不同阶段产生特定事件时的回调。

package com.dada.test.config;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * spring 容器启动之后执行方法
 * @author: ztd
 * @date 2019/4/25 下午7:00
 */
@Component
public class SpringEventCheck implements ApplicationListener<ApplicationEvent> {
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if(event instanceof ContextClosedEvent ){
            System.out.println(event.getClass().getSimpleName()+" 事件已发生!");
        }else if(event instanceof ContextRefreshedEvent){
            System.out.println(event.getClass().getSimpleName()+" 事件已发生!");
        }else if(event instanceof ContextStartedEvent){
            System.out.println(event.getClass().getSimpleName()+" 事件已发生!");
        }else if(event instanceof ContextStoppedEvent){
            System.out.println(event.getClass().getSimpleName()+" 事件已发生!");
        }else{
            System.out.println("有其它事件发生:"+event.getClass().getName());
        }
    }
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐