• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

springBoot启动时让方法自动执行的几种实现方式

springboot 搞代码 4年前 (2022-01-09) 33次浏览 已收录 0个评论

在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之前,将通知所有s<span>本文来源gaodai#ma#com搞*代#码9网#</span>ervletContextListener上下文初始化。
   */
  @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启动时让方法自动执行的几种实现方式的文章就介绍到这了,更多相关springBoot启动时自动执行内容请搜索搞代码以前的文章或继续浏览下面的相关文章希望大家以后多多支持搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:springBoot启动时让方法自动执行的几种实现方式

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址