美文网首页程序员Spring Boot
Spring Boot (番外篇)启动后执行特定的方法

Spring Boot (番外篇)启动后执行特定的方法

作者: 葉糖糖 | 来源:发表于2020-06-27 16:05 被阅读0次

    经常遇到一种需求,在项目启动之后需要自动执行某一些特定的方法。那么在Spring Boot中可以怎么处理类似的需求呢?想一想。

    一、简单实用的ApplicationRunner

    这个接口中有个run方法,我们只要实现这个方法即可。首先要知道,ApplicationRunner是Spring Boot中的启动加载类,如果有启动的时候加载初始化参数可以实现这个类中的run方法。

    package com.nicy.turing.util;
    
    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.stereotype.Component;
    
    /**
     * @author SugarYe
     * @date 2020年06月27日 11:06
     */
    @Component
    public class LogUtil implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments args) throws Exception {
            System.out.println("Turing Project is run!");
    
        }
    }
    

    二、天下武功唯独写轮眼厉害,CommandLineRunner

    CommandLineRunner也是接口,只要实现run方法就行。

    package com.nicy.turing.util;
    
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    /**
     * @author SugarYe
     * @date 2020年06月27日 11:36
     */
    @Component
    public class UserLoginUtil implements CommandLineRunner {
    
        @Override
        public void run(String... args) throws Exception {
            System.out.println("这是一个CommandLineRunner接口");
            //迭代参数
            for (String arg : args){
                System.out.println(arg +"");
            }
        }
    }
    
    

    三、友情提示

    如果实现了多个容器启动加载函数,那么可以通过@Order(value = 2)注解来控制函数执行的顺序。

    相关文章

      网友评论

        本文标题:Spring Boot (番外篇)启动后执行特定的方法

        本文链接:https://www.haomeiwen.com/subject/lzxvfktx.html