温馨提示×

温馨提示×

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

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

springBoot启动时让方法自动执行的方法

发布时间:2021-03-08 13:53:24 来源:亿速云 阅读:236 作者:TREX 栏目:开发技术

本篇内容介绍了“springBoot启动时让方法自动执行的方法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

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

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

@Component
public class TestStarted implements ServletContextAware {
  /**
   * 在填充普通bean属性之后但在初始化之前调用
   * 类似于initializingbean的afterpropertiesset或自定义init方法的回调
   *
   */
  @Override
  public void setServletContext(ServletContext servletContext) {
    System.out.println("setServletContext方法");
  }
}

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

2.实现ServletContextListener接口

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

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

@Component
public class Test2 {
  //静态代码块会在依赖注入后自动执行,并优先执行
  static{
    System.out.println("---static--");
  }
  /**
   * @Postcontruct'在依赖注入完成后自动调用
   */
  @PostConstruct
  public static void haha(){
    System.out.println("@Postcontruct'在依赖注入完成后自动调用");
  }
}

4.实现ApplicationRunner接口

  /**
   * 用于指示bean包含在SpringApplication中时应运行的接口。可以定义多个applicationrunner bean
   * 在同一应用程序上下文中,可以使用有序接口或@order注释对其进行排序。
   */
  @Override
  public void run(ApplicationArguments args) throws Exception {
    System.out.println("ApplicationRunner的run方法");
  }

5.实现CommandLineRunner接口

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

“springBoot启动时让方法自动执行的方法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

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

AI