Spring Boot (番外篇)启动后执行特定的方法
2020-06-27 本文已影响0人
葉糖糖
经常遇到一种需求,在项目启动之后需要自动执行某一些特定的方法。那么在Spring Boot中可以怎么处理类似的需求呢?想一想。
一、简单实用的ApplicationRunner
这个接口中有个
run
方法,我们只要实现这个方法即可。首先要知道,ApplicationRunner是Spring Boot中的启动加载类,如果有启动的时候加载初始化参数可以实现这个类中的run
方法。
package com.nicy.turing.util;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
/**
* @author SugarYe
* @date 2020年06月27日 11:06
*/
@Component
public class LogUtil implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Turing Project is run!");
}
}
二、天下武功唯独写轮眼厉害,CommandLineRunner
CommandLineRunner也是接口,只要实现
run
方法就行。
package com.nicy.turing.util;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
* @author SugarYe
* @date 2020年06月27日 11:36
*/
@Component
public class UserLoginUtil implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("这是一个CommandLineRunner接口");
//迭代参数
for (String arg : args){
System.out.println(arg +"");
}
}
}
三、友情提示
如果实现了多个容器启动加载函数,那么可以通过@Order(value = 2)
注解来控制函数执行的顺序。