温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot怎么实现启动时自动执行代码

发布时间:2022-02-17 13:42:45 来源:亿速云 阅读:327 作者:iii 栏目:开发技术

这篇文章主要介绍了SpringBoot怎么实现启动时自动执行代码的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringBoot怎么实现启动时自动执行代码文章都会有所收获,下面我们一起来看看吧。

    前言

    目前开发的SpringBoot项目在启动的时候需要预加载一些资源。而如何实现启动过程中执行代码,或启动成功后执行,是有很多种方式可以选择,我们可以在static代码块中实现,也可以在构造方法里实现,也可以使用@PostConstruct注解实现。

    当然也可以去实现Spring的ApplicationRunner与CommandLineRunner接口去实现启动后运行的功能。在这里整理一下,在这些位置执行的区别以及加载顺序。

    java自身的启动时加载方式

    static代码块

    static静态代码块,在类加载的时候即自动执行。

    构造方法

    在对象初始化时执行。执行顺序在static静态代码块之后。

    Spring启动时加载方式

    @PostConstruct注解

    PostConstruct注解使用在方法上,这个方法在对象依赖注入初始化之后执行。

    ApplicationRunner和CommandLineRunner

    SpringBoot提供了两个接口来实现Spring容器启动完成后执行的功能,两个接口分别为CommandLineRunner和ApplicationRunner。

    这两个接口需要实现一个run方法,将代码在run中实现即可。这两个接口功能基本一致,其区别在于run方法的入参。ApplicationRunner的run方法入参为ApplicationArguments,为CommandLineRunner的run方法入参为String数组。

    何为ApplicationArguments

    官方文档解释为:

    ”Provides access to the arguments that were used to run a SpringApplication.

    在Spring应用运行时使用的访问应用参数。即我们可以获取到SpringApplication.run(…)的应用参数。

    Order注解

    当有多个类实现了CommandLineRunner和ApplicationRunner接口时,可以通过在类上添加@Order注解来设定运行顺序。

    代码测试

    为了测试启动时运行的效果和顺序,编写几个测试代码来运行看看。

    TestPostConstruct

    @Component
    public class TestPostConstruct {
    
        static {
            System.out.println("static");
        }
        public TestPostConstruct() {
            System.out.println("constructer");
        }
    
        @PostConstruct
        public void init() {
            System.out.println("PostConstruct");
        }
    }

    TestApplicationRunner

    @Component
    @Order(1)
    public class TestApplicationRunner implements ApplicationRunner{
        @Override
        public void run(ApplicationArguments applicationArguments) throws Exception {
            System.out.println("order1:TestApplicationRunner");
        }
    }

    TestCommandLineRunner

    @Component
    @Order(2)
    public class TestCommandLineRunner implements CommandLineRunner {
        @Override
        public void run(String... strings) throws Exception {
            System.out.println("order2:TestCommandLineRunner");
        }
    }

    执行结果

    SpringBoot怎么实现启动时自动执行代码

    关于“SpringBoot怎么实现启动时自动执行代码”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“SpringBoot怎么实现启动时自动执行代码”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI