springboot 项目启动完成后执行指定代码的两种方式
1.情景展示
当我们想在springboot在项目启动完成后,会有执行某些代码的需求,比如说:在控制台打印项目的相关信息,如何实现?
实现方式有两种,具体如下:
2.实现ApplicationRunner接口
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.net.Inet4Address;
import java.net.UnknownHostException;
/**
* springboot启动后自动执行方法
* @description:
* @author: Marydon
* @date: 2020-12-10 11:19
* @version: 1.0
* @email: marydon20170307@163.com
*/
@Slf4j
@Component
// 当有多个类实现ApplicationRunner接口时,可以指定其执行顺序,值越小优先级越高
@Order(value = 1)
public class BillApplicationRunner implements ApplicationRunner {
@Resource
Environment environment;
/*
* 启动结束后会立即执行的方法
* @attention:
* @date: 2020年12月10日 0010 11:21
* @param: args
* @return: void
*/
@Override
public void run(ApplicationArguments args) {
log.info("通过实现ApplicationRunner接口,在spring boot项目启动后打印参数");
try {
String contextPath = environment.getProperty("server.servlet.context-path");
if (contextPath == null) {
contextPath = "/";
}
log.info("项目启动完毕,访问地址是:{}://{}:{}{}", "http", Inet4Address.getLocalHost().getHostAddress(), environment.getProperty("server.port"), contextPath);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
说明:当有多个类实现ApplicationRunner接口时,可以使用@Order注解指定其执行顺序,值越小优先级越高
3.实现CommandLineRunner接口
import code.marydon.encapsulation.http.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* springboot启动后自动执行方法
* @description:
* @author: Marydon
* @date: 2022/1/27 16:54
* @version: 1.0
* @email: marydon20170307@163.com
*/
@Slf4j
@Component
// 当有多个类实现CommandLineRunner接口时,可以指定其执行顺序,值越小优先级越高
@Order(value = 2)
public class BillCommandLineRunner implements CommandLineRunner {
@Resource
Environment environment;
/*
* 启动结束后会立即执行的方法
* @attention:
* @date: 2022/1/27 16:53
* @param: args
* @return: void
*/
@Override
public void run(String... args) {
log.info("通过实现CommandLineRunner接口,在spring boot项目启动后打印参数");
IpUtils.getAccessPath(environment);
}
}
说明:当有多个类实现CommandLineRunner接口时,可以使用@Order注解指定其执行顺序,值越小优先级越高。
另外,当项目中同时实现了ApplicationRunner和CommondLineRunner接口时,可使用Order注解或实现Ordered接口来指定执行顺序,值越小越先执行。
本文来自博客园,作者:Marydon,转载请注明原文链接:https://www.cnblogs.com/Marydon20170307/p/15850449.html