Spring启动后进行一些初始化的方式汇总

本文来聊一下在spring中,当spring 容器启动后,我们有几种初始化操作的方式。

在spring 容器中有一个 Persion对象名字叫张三,需要在spring容器启动后调用它的run方法。代码如下


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PersonConfig {

    @Bean
    public Person person(){
        Person person = new Person();
        person.setName("张三");
        person.setAge(18);
        return person;
    }
}

一、ContextRefreshedEvent事件

ContextRefreshedEvent:是Spring容器初始化完成后调用的事件。
ContextRefreshedEvent的父类是ApplicationContextEvent,是一个事件。所以我们通过ApplicationListener来实现。

代码如下:

import com.example.springbootdemo.bean.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class PersonAfterListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private Person person;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        person.run("ContextRefreshedEvent");
    }
}

输出结果:

输出结果

二、PostConstruct 注解

PostConstruct注解修饰的方式,是在spring容器启动时运行的。优先级大于ContextRefreshedEvent事件。

代码如下:

import com.example.springbootdemo.bean.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class PersonAfterPostConstruct {
    @Autowired
    private Person person;

    @PostConstruct
    public void postConstruct(){
        person.run("PostConstruct");
    }
}

输出结果:

输出结果


由此可见,PostConstruct优先级大于ContextRefreshedEvent事件。

三、InitializingBean

InitializingBean是spring容器在启动并初始化好内部示例后调用的,用来最终为总体bean添加最后属性和操作。

官方原话:This method allows the bean instance to perform validation of its overall configuration and final initialization when all bean properties have been set.

代码如下:

import com.example.springbootdemo.bean.Person;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PersonAfterInitializingBean implements InitializingBean {
    @Autowired
    private Person person;

    @Override
    public void afterPropertiesSet() throws Exception {
        person.run("InitializingBean");
    }
}

输出结果:

输出结果

四、init-method方法

这种方法有一定的局限性,并且可能会覆盖曾经的init操作,需要慎用。

Bean在加载到Spring容器中时需要先将Bean的定义信息抽象为BeanDefinition,其中有一个属性init-method代表将来Bean初始化时要调用的方法。

我们通过BeanFactoryPostProcessor来注入init-method方法,并且该方法必须是没有参数的

代码如下:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

@Component
public class PersonAfterInit implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        BeanDefinition person = beanFactory.getBeanDefinition("person");
        person.setInitMethodName("run");
    }
}

输出结果:

输出结果

五 、实现 SmartInitializingSingleton 接口

SmartInitializingSingleton是Bean容器在初始化所有非懒加载的单例Bean后调用的方法。

代码如下:

import com.example.springbootdemo.bean.Person;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PersonAfterSmartInitializingSingleton implements SmartInitializingSingleton {
    @Autowired
    private Person person;

    @Override
    public void afterSingletonsInstantiated() {
        person.run("SmartInitializingSingleton");
    }
}

输出结果:

输出结果

六、重写 onRefresh()方法

这个我实在是不会,但我不藏着掖着,告诉你也能实现。

七、CommandLineRunner(仅限Spring Boot)

CommandLineRunner 是一个Spring boot 接口,在应用初始化后执行,且仅会执行一次。可以用来打印项目中配置文件的参数,方便排查问题。

代码如下:

import com.example.springbootdemo.bean.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class PersonAfterCommandLineRunner implements CommandLineRunner {
    @Autowired
    private Person person;

    @Override
    public void run(String... args) throws Exception {
        person.run("CommandLineRunner");
    }
}

输出结果:

输出结果

八、SpringApplicationRunListener(仅限Spring boot)

SpringBoot的生命周期事件监听方法,需要搭配resource/META-INF/spring.factories 文件使用。

代码如下:

JAVA代码:

import com.example.springbootdemo.bean.Person;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.time.Duration;


public class PersonAfterSpringApplicationRunListener implements SpringApplicationRunListener {
    private final SpringApplication application;
    private final String[] args;

    public PersonAfterSpringApplicationRunListener(SpringApplication application, String[] args) {
        this.application = application;
        this.args = args;
    }

    @Override
    public void starting(ConfigurableBootstrapContext bootstrapContext) {
        /*
         * Person has not been registered
         */
//        Person person = bootstrapContext.get(Person.class);
//        person.run("SpringApplicationRunListener:starting");
    }

    @Override
    public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
        /*
         * Person has not been registered
         */
//        Person person = bootstrapContext.get(Person.class);
//        person.run("SpringApplicationRunListener:environmentPrepared");
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        /*
         * Person has not been registered
         */
//        Person person = context.getBean(Person.class);
//        person.run("SpringApplicationRunListener:contextPrepared");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        /*
         * Person has not been registered
         */
//        Person person = context.getBean(Person.class);
//        person.run("SpringApplicationRunListener:contextLoaded");
    }

    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
        Person person = context.getBean(Person.class);
        person.run("SpringApplicationRunListener:started");
    }

    @Override
    public void ready(ConfigurableApplicationContext context, Duration timeTaken) {
        Person person = context.getBean(Person.class);
        person.run("SpringApplicationRunListener:ready");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        Person person = context.getBean(Person.class);
        person.run("SpringApplicationRunListener:failed");
    }
}

spring.factories

org.springframework.boot.SpringApplicationRunListener=com.example.springbootdemo.impl.PersonAfterSpringApplicationRunListener

输出结果:

输出结果

总结:

执行优先级:init-Method >> InitializingBean >> PostConstruct >> SmartInitializingSingleton >> ContextRefreshedEvent >> SpringApplicationRunListener:started >> CommandLineRunner >> SpringApplicationRunListener:ready

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


学习编程是顺着互联网的发展潮流,是一件好事。新手如何学习编程?其实不难,不过在学习编程之前你得先了解你的目的是什么?这个很重要,因为目的决定你的发展方向、决定你的发展速度。
IT行业是什么工作做什么?IT行业的工作有:产品策划类、页面设计类、前端与移动、开发与测试、营销推广类、数据运营类、运营维护类、游戏相关类等,根据不同的分类下面有细分了不同的岗位。
女生学Java好就业吗?女生适合学Java编程吗?目前有不少女生学习Java开发,但要结合自身的情况,先了解自己适不适合去学习Java,不要盲目的选择不适合自己的Java培训班进行学习。只要肯下功夫钻研,多看、多想、多练
Can’t connect to local MySQL server through socket \'/var/lib/mysql/mysql.sock问题 1.进入mysql路径
oracle基本命令 一、登录操作 1.管理员登录 # 管理员登录 sqlplus / as sysdba 2.普通用户登录
一、背景 因为项目中需要通北京网络,所以需要连vpn,但是服务器有时候会断掉,所以写个shell脚本每五分钟去判断是否连接,于是就有下面的shell脚本。
BETWEEN 操作符选取介于两个值之间的数据范围内的值。这些值可以是数值、文本或者日期。
假如你已经使用过苹果开发者中心上架app,你肯定知道在苹果开发者中心的web界面,无法直接提交ipa文件,而是需要使用第三方工具,将ipa文件上传到构建版本,开...
下面的 SQL 语句指定了两个别名,一个是 name 列的别名,一个是 country 列的别名。**提示:**如果列名称包含空格,要求使用双引号或方括号:
在使用H5混合开发的app打包后,需要将ipa文件上传到appstore进行发布,就需要去苹果开发者中心进行发布。​
+----+--------------+---------------------------+-------+---------+
数组的声明并不是声明一个个单独的变量,比如 number0、number1、...、number99,而是声明一个数组变量,比如 numbers,然后使用 nu...
第一步:到appuploader官网下载辅助工具和iCloud驱动,使用前面创建的AppID登录。
如需删除表中的列,请使用下面的语法(请注意,某些数据库系统不允许这种在数据库表中删除列的方式):
前不久在制作win11pe,制作了一版,1.26GB,太大了,不满意,想再裁剪下,发现这次dism mount正常,commit或discard巨慢,以前都很快...
赛门铁克各个版本概览:https://knowledge.broadcom.com/external/article?legacyId=tech163829
实测Python 3.6.6用pip 21.3.1,再高就报错了,Python 3.10.7用pip 22.3.1是可以的
Broadcom Corporation (博通公司,股票代号AVGO)是全球领先的有线和无线通信半导体公司。其产品实现向家庭、 办公室和移动环境以及在这些环境...
发现个问题,server2016上安装了c4d这些版本,低版本的正常显示窗格,但红色圈出的高版本c4d打开后不显示窗格,
TAT:https://cloud.tencent.com/document/product/1340