美文网首页
springboot项目启动后执行方法

springboot项目启动后执行方法

作者: 一叶知秋_038b | 来源:发表于2019-10-29 15:49 被阅读0次

    1.CommandLineRunner :

    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    @Component
    public class MyCommandLineRunner implements CommandLineRunner{
        @Override
        public void run(String... var1) throws Exception{
            System.out.println("Runner!");
        }
    }
    

    2.ApplicationRunner :

    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.stereotype.Component;
    
    @Component
    public class MyApplicationRunner implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments var1) throws Exception{
            System.out.println("Runner!");
        }
    }
    

    如果想要指定启动方法执行的顺序,可以通过实现org.springframework.core.Ordered接口或者使用org.springframework.core.annotation.Order注解来实现。

    1.Ordered接口:

    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.core.Ordered;
    import org.springframework.stereotype.Component;
    
    @Component
    public class MyApplicationRunner implements ApplicationRunner,Ordered{
        @Override
        public int getOrder(){
            return 1;//通过设置这里的数字来知道指定顺序
        }
    
        @Override
        public void run(ApplicationArguments var1) throws Exception{
            System.out.println("Runner!");
        }
    }
    

    2.Order注解实现方式:

    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.core.Ordered;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
    
    @Component
    @Order(value = 1)
    public class MyApplicationRunner implements ApplicationRunner{
    
        @Override
        public void run(ApplicationArguments var1) throws Exception{
            System.out.println("Runner!");
        }
    }
    

    相关文章

      网友评论

          本文标题:springboot项目启动后执行方法

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