zoukankan      html  css  js  c++  java
  • SpringBoot启动时让方法自动执行的几种实现方式

    在springBoot中我们有时候需要让项目在启动时提前加载相应的数据或者执行某个方法,那么实现提前加载的方式有哪些呢?接下来我带领大家逐个解答

    1.实现ServletContextAware接口并重写其setServletContext方法

    实现ServletContextAware

    注意:该方法会在填充完普通Bean的属性,但是还没有进行Bean的初始化之前执行

    2.实现ServletContextListener接口

    1 /**
    2      * 在初始化Web应用程序中的任何过滤器或servlet之前,将通知所有servletContextListener上下文初始化。
    3      */
    4     @Override
    5     public void contextInitialized(ServletContextEvent sce) {
    6         //ServletContext servletContext = sce.getServletContext();
    7         System.out.println("执行contextInitialized方法");
    8     }
    实现ServletContextListener接口

    3.将要执行的方法所在的类交个spring容器扫描(@Component),并且在要执行的方法上添加@PostConstruct注解或者静态代码块执行(推荐)

     1 @Component
     2 public class Test2 {
     3     //静态代码块会在依赖注入后自动执行,并优先执行
     4     static{
     5         System.out.println("---static--");
     6     }
     7     /**
     8      *  @Postcontruct’在依赖注入完成后自动调用
     9      */
    10     @PostConstruct
    11     public static void haha(){
    12         System.out.println("@Postcontruct’在依赖注入完成后自动调用");
    13     }
    14 }
    @Postcontruct

    4.实现ApplicationRunner接口 或 实现CommandLineRunner接口(推荐)

    业务场景:
    应用服务启动时,加载一些数据和执行一些应用的初始化动作。如:删除临时文件,清除缓存信息,读取配置文件信息,数据库连接等。
    1、当接口有多个实现类时,提供了@order注解实现自定义执行顺序,也可以实现Ordered接口来自定义顺序。
    注意:数字越小,优先级越高,也就是@Order(1)注解的类会在@Order(2)注解的类之前执行。
    两者的区别在于:
    ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。想要更详细地获取命令行参数,那就使用ApplicationRunner接口
     

    1 /**
    2      * 用于指示bean包含在SpringApplication中时应运行的接口。可以定义多个applicationrunner bean
    3      * 在同一应用程序上下文中,可以使用有序接口或@order注释对其进行排序。
    4      */
    5     @Override
    6     public void run(ApplicationArguments args) throws Exception {
    7         System.out.println("ApplicationRunner的run方法");
    8     }
    实现ApplicationRunner接口
    1 /**
    2      * 用于指示bean包含在SpringApplication中时应运行的接口。可以在同一应用程序上下文中定义多个commandlinerunner bean,并且可以使用有序接口或@order注释对其进行排序。
    3      * 如果需要访问applicationArguments而不是原始字符串数组,请考虑使用applicationrunner。
    4      * 
    5      */
    6     @Override
    7     public void run(String... ) throws Exception {
    8         System.out.println("CommandLineRunner的run方法");
    9     }
    实现CommandLineRunner接口

    转自:https://javazhiyin.blog.csdn.net/article/details/113533177

    https://blog.csdn.net/weixin_38362455/article/details/83023025

  • 相关阅读:
    使用 libevent 和 libev 提高网络应用性能
    在PHP中PDO解决中文乱码问题的一些补充
    apache重写规则详解
    Apache的配置
    正则表达式30分钟入门教程
    LVS+keepalived搭建负载均衡
    php判断终端是手机还是电脑访问网站代码
    nginx 502 bad gateway
    算法复习-深度优先遍历和回溯法的关系
    分支限界法和回溯法对比
  • 原文地址:https://www.cnblogs.com/zt007/p/14961816.html
Copyright © 2011-2022 走看看