zoukankan      html  css  js  c++  java
  • spring boot 启动加载 CommandLineRunner @PostConstruct

    spring boot 启动加载

    CommandLineRunner

    在项目中,经常有这样的需求,我们需要在项目启动完立即初始化一些数据(比如缓存等),以便后面调用使用。spring boot可以通过CommandLineRunner接口实现启动加载功能。

    新建一个Java文件,类需要用Component声明下,需要实现CommandLineRunner接口,然后重写run方法,在run方法内编写需要加载的内容。
    代码如下:

    package com.study.test.startup;
    
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    /**
     * @Description: 初始化启动类
     * @Author: chen
     * @Date: Created in 2019/2/22
     */
    @Component
    public class InitStarter implements CommandLineRunner{
    
        @Override
        public void run(String... args) throws Exception {
            System.out.println("CommandLineRunner example start");
        }
    }

    启动项目,运行结果证明:CommandLineRunner会在服务启动之后被立即执行

     总结:
    CommandLineRunner会在服务启动之后被立即执行。
    CommandLineRunner可以有多个,且多个直接可以用order注解进行排序。

    @PostConstruct

    • 另一个需求是,在类加载的时候,为当前类初始化一些数据,那么可以使用@PostConstruct注解。 Servlet中增加了两个影响Servlet生命周期的注解,@PostConstruct和@PreDestroy,这两个注解被用来修饰一个非静态的void()方法。
    • 在一个类内,如果有构造器(Constructor ),有@PostConstruct,还有@Autowired,他们的先后执行顺序为Constructor >> @Autowired >> @PostConstruct。
    • 因为一个有声明注解的类文件(必须有声明,这样在项目初始化时候才会注入),在项目启动后,会对对象进行依赖注入,而初始化的动作会依赖于对象,所以假象上看,也类似于项目启动就会执行的操作,因此,我们也可以通过这样的形式,对数据进行初始化。

    说明一下,@PostConstruct更针对性于当前类文件,而CommandLineRunner更服务于整个项目。所以在我们使用中,可根据自己的使用场景来进行选择用这两种方式来实现初始化。

    package com.study.test.postConstruct;
    
    import org.springframework.stereotype.Component;
    
    import javax.annotation.PostConstruct;
    
    /**
     * @Description:
     * @Author: chen
     * @Date: Created in 2019/2/25
     */
    @Component
    public class Init {
    
        @PostConstruct
        private void init(){
            System.out.println("PostConstruct 注解 初始化数据.");
        }
    }

    执行结果:

    说明一下:执行结果可以看到,在项目还没有启动成功的时候,@PostConstruct已经执行完了,因为@PostConstruct是在Init类注入完成后立马执行的,它并不依赖于项目的启动。

    故乡明
  • 相关阅读:
    为什么要使用Handler
    使用Java中的Timer和TimerTask
    Top子句对查询计划的影响
    一个单表死锁的示例
    tracer token 追踪标记
    DDL Trigger
    事物复制的troubleshooting 1
    在分发服务器上查看信息
    将windows 2003 sp2的cluster升级到windows 2008 r2
    DistributionDB过大的原因
  • 原文地址:https://www.cnblogs.com/luweiweicode/p/15130498.html
Copyright © 2011-2022 走看看