springboot启动时自动打开浏览器

2022-12-24  本文已影响0人  晓晓_1931

方法一

一、yml配置文件中加

server:
  port: 8088
  servlet:
   context-path: /cartoon 
# 启动项目自动打开浏览器
openProject:
  isOpen: true
  cmd: cmd   /c   start
  web:
    openUrl: http://localhost:${server.port}/cartoon/#

二、添加配置类

package com.xx.cartoon.config; 

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RunConfig implements CommandLineRunner {

    @Value("${openProject.isOpen}")
    private boolean isOpen;

    @Value("${openProject.web.openUrl}")
    private String openUrl;

    @Value("${openProject.cmd}")
    private String cmd;

    @Override
    public void run(String... args){
        if(isOpen){
            String runCmd = cmd + " " + openUrl ;
            System.out.println("运行的命令: " + runCmd);
            Runtime run = Runtime.getRuntime();
            try {
                run.exec(runCmd);
                System.out.println("启动浏览器打开项目成功");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("启动项目自动打开浏览器失败");
            }
        }
    }
}

方法二

@SpringBootApplication
public class SpringbootApplication { 
    public static void main(String[] args) { 
 
            String port ="8088" ;
            for (String arg : args) { 
                System.out.println("arg:"+arg);
                if (arg.startsWith(portPrefix)) {
                    port = arg.substring(portPrefix.length()); 
                }
            }
         
            SpringApplication.run(SpringbootApplication.class, args);
            
           String portPrefix = "--server.port=";
            try {
                Runtime.getRuntime().exec("cmd /c start http://localhost:" + port +"/index");
            } catch (IOException e) {
                e.printStackTrace();
            }
        
    }

}
上一篇下一篇

猜你喜欢

热点阅读