原文链接: https://www.lskyf.com/post/1466
需求描述
开发时每次手动打开浏览器,然后输如url,打开相应的页面。感觉不太方便。可以实现打印启动链接并自动打开想要打开的页面。
材料预览
-
spring boot web环境:使用runner监听服务启动实现业务逻辑
-
chrome浏览器exe文件(浏览器安装路径):可以使用其他浏览器
-
window cmd命令:目的是自定打开页面
-
application-dev.properties文件:配置指定页面,灵活调整,并且控制在开发环境使用。
代码
StartUpRunner.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @description:
* @author: 猿份哥
* @date: 2023/7/22
**/
@Component
public class StartUpRunner implements ApplicationRunner {
@Value("${server.port}")
private String port;
@Value("${server.address}")
private String host;
@Value("${spring.profiles.active}")
String profiles;
@Value("${open.chrome.url}")
String chrome;
@Value("${open.page}")
String page;
@Override
public void run(ApplicationArguments args) throws IOException {
if ("dev".equals(profiles)){
String url = "http://" + host + ":" + port;
System.out.println("服务已启动: " + url);
String cmd=chrome+" "+ url+"/"+page;
Runtime run = Runtime.getRuntime();
run.exec(cmd);
}
}
}
application-dev.properties文件
#chrome安装路径实现自动打开
open.chrome.url=C:\\Users\\yuanfenge\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe
#配置想自动打开的页面
open.page="qrcode.html"
application.properties文件,指定开发环境,或者启动的时候命令配置
server.port=8080
server.address=localhost
spring.profiles.active=dev
说明
server.port=8080,server.address=localhost这两个需要配置否则可能获取不到信息
注意:本文归作者所有,未经作者允许,不得转载