继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

SpringBoot启动执行初始化代码

Qyouu
关注TA
已关注
手记 311
粉丝 87
获赞 413

利用CommandLineRunner、EnvironmentAware在Spring boot启动时执行初始化代码

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.context.EnvironmentAware;import org.springframework.core.annotation.Order;import org.springframework.core.env.Environment;import org.springframework.stereotype.Component;import java.util.List;@Component//如果有多个这样的类时,可以通过Order指定执行顺序,数值越小执行优先级越高@Order(value = 0)public class InitSystemConfig implements CommandLineRunner, EnvironmentAware {    /*
     * 在服务启动后执行,会在@Bean实例化之后执行,故如果@Bean需要依赖这里的话会出问题
     */
    @Override
    public void run(String... args) {        //这里可以根据数据库返回结果创建一些对象、启动一些线程等
        

    }    /*
     * 在SystemConfigDao实例化之后、@Bean实例化之前执行
     * 常用于读取数据库配置以供其它bean使用
     * environment对象可以获取配置文件的配置,也可以把配置设置到该对象中
     */
    @Override
    public void setEnvironment(Environment environment) {

    }
}

github主页:https://github.com/xvjialing



作者:褪色的记忆1994
链接:https://www.jianshu.com/p/7826ce1d95ee

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP