美文网首页
springboot启动时自动打开浏览器

springboot启动时自动打开浏览器

作者: 晓晓_1931 | 来源:发表于2022-12-24 04:00 被阅读0次

    方法一

    一、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();
                }
            
        }
    
    }
    

    相关文章

      网友评论

          本文标题:springboot启动时自动打开浏览器

          本文链接:https://www.haomeiwen.com/subject/jvmiqdtx.html