代码额外配置(比平常写代码)
监听启动完毕 获取content path & port
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
@Configurable
public class AppListener implements ApplicationRunner{
@Autowired
Environment environment;
//重写 启动完毕后调用
@Override
public void run(ApplicationArguments args) throws Exception {
int run_prot = get_run_prot(environment);
String cnt_path = get_run_cnt_path(environment);
open_browser(run_prot,cnt_path);
}
//打开浏览器
public static boolean open_browser(int port,String cnt_path){
String cmd = "cmd /c start http://localhost:" + port + cnt_path;
try {
Process exec = Runtime.getRuntime().exec(cmd);
exec.waitFor();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
};
//content path
public static String get_run_cnt_path( Environment environment){
return environment.getProperty("server.servlet.context-path");
}
//port
public static int get_run_prot( Environment environment){
String port = environment.getProperty("local.server.port");
return Integer.parseInt(port);
}
}
启动类
- 将spring run的返回值保存,监听浏览器关闭,浏览器关闭的时候关闭服务
ConfigurableApplicationContext context = SpringApplication.run(DeskAppApplication.class, args);
// 关闭程序 SpringApplication.exit(DeskAppApplication.context,() -> 0);
springboot 启动端口使用随机启动端口方式,防止端口冲突
server.port=0
# 0 代表随机启动一个可用端口
#server.port=8080
打包(Windows)
- 启动bat(start.bat 放在jar包统计目录,同时将JRE也放在该目录下)
@echo off
start .jrebinjava.exe -jar print_app.jar
将启动bat 转成exe(不知道如何设置ico或者找到更好的方案)
- 所要工具 Bat_To_Exe_Converter.exe
- Bat_To_Exe_Converter
将jre、启动文件(bat转的exe)、springboot打包后的jar整体打包成EXE