当前位置: 移动技术网 > IT编程>开发语言>Java > 详解Spring Boot 项目启动时执行特定方法

详解Spring Boot 项目启动时执行特定方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

springboot给我们提供了两种“开机启动”某些方法的方式:applicationrunner和commandlinerunner。

这两种方法提供的目的是为了满足,在项目启动的时候立刻执行某些方法。我们可以通过实现applicationrunner和commandlinerunner,来实现,他们都是在springapplication 执行之后开始执行的。

commandlinerunner接口可以用来接收字符串数组的命令行参数,applicationrunner 是使用applicationarguments 用来接收参数的,貌似后者更牛逼一些。

先看看commandlinerunner :

package com.springboot.study;

import org.springframework.boot.commandlinerunner;
import org.springframework.stereotype.component;

/**
 * created by pangkunkun on 2017/9/3.
 */
@component
public class mycommandlinerunner implements commandlinerunner{

  @override
  public void run(string... var1) throws exception{
    system.out.println("this will be execute when the project was started!");
  }
}

applicationrunner :

package com.springboot.study;

import org.springframework.boot.applicationarguments;
import org.springframework.boot.applicationrunner;
import org.springframework.stereotype.component;

/**
 * created by pangkunkun on 2017/9/3.
 */
@component
public class myapplicationrunner implements applicationrunner {

  @override
  public void run(applicationarguments var1) throws exception{
    system.out.println("myapplicationrunner class will be execute when the project was started!");
  }

}

这两种方式的实现都很简单,直接实现了相应的接口就可以了。记得在类上加@component注解。

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

这里我们以applicationrunner 为例来分别实现。

ordered接口:

package com.springboot.study;

import org.springframework.boot.applicationarguments;
import org.springframework.boot.applicationrunner;
import org.springframework.core.ordered;
import org.springframework.stereotype.component;

/**
 * created by pangkunkun on 2017/9/3.
 */
@component
public class myapplicationrunner implements applicationrunner,ordered{


  @override
  public int getorder(){
    return 1;//通过设置这里的数字来知道指定顺序
  }

  @override
  public void run(applicationarguments var1) throws exception{
    system.out.println("myapplicationrunner1!");
  }

}

order注解实现方式:

package com.springboot.study;

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;

/**
 * created by pangkunkun on 2017/9/3.
 * 这里通过设定value的值来指定执行顺序
 */
@component
@order(value = 1)
public class myapplicationrunner implements applicationrunner{

  @override
  public void run(applicationarguments var1) throws exception{
    system.out.println("myapplicationrunner1!");
  }

}

这里不列出其他对比方法了,自己执行下就好。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网