CommandLineRunner初体验(打印swagger路径、端口号、数据库连接等)
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.net.Inet4Address;
/**
* @Description: 监听端口bean
* @author: be.inisghted
* @create: 2024/8/8 15:09
* @since 1.0.0
*/
@Slf4j
@Component
public class AppRunner implements CommandLineRunner {
@Autowired
private Environment environment;
@Autowired
private DataSource dataSource;
@Override
public void run(String... args) throws Exception {
log.info("========= 打印启动信息 =========");
// 打印应用端口
log.info(("端口号: " + environment.getProperty("server.http.port")));
// 打印当前环境
log.info("当前环境: " + environment.getProperty("spring.profiles.active"));
log.info("context-path: " + environment.getProperty("server.servlet.context-path"));
// 打印JDK版本
log.info("JDK 版本: " + System.getProperty("java.version"));
log.info("数据库连接{}",dataSource.getConnection() == null ? ":失败" : ":成功");
log.info("swagger访问链接: " + "http://" + Inet4Address.getLocalHost().getHostAddress() + ":" + environment.getProperty("server.http.port") + environment.getProperty("server.servlet.context-path") + "/doc.html");
log.info("========= 打印启动信息结束 =========");
}
}