版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37465368/article/details/82535119
Springboot给我们提供了两种“开机启动”某些方法的方式:ApplicationRunner和CommandLineRunner。
在项目启动的时候立即执行否个方法:
我们可以通过实现ApplicationRunner和CommandLineRunner,来实现,他们都是在SpringApplication 执行之后开始执行的。
CommandLineRunner接口可以用来接收字符串数组的命令行参数,ApplicationRunner 是使用ApplicationArguments 用来接收参数的。
这两种方式的实现都很简单,直接实现了相应的接口就可以了。记得在类上加@Component注解。
如果想要指定启动方法执行的顺序,可以通过实现org.springframework.core.Ordered接口或者使用org.springframework.core.annotation.Order注解来实现。
示例:
@Component
public class Runner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
//此处为了记录一下线程的使用,没任何意义
new Thread(() -> {
try {
execute();
} catch (Exception e) {
e.printStackTrace();
}
}
).start();
}
private void execute() throws Exception {
System.out.println("hhahahahha");
}
记两个指令
打包:mvn clean package -Dmaven.test.skip=true
后台执行(➕&):nohup java -jar name.jar &