当前位置: 代码网 > it编程>编程语言>Java > springboot项目启动后,自动打开默认浏览器的方式

springboot项目启动后,自动打开默认浏览器的方式

2025年11月22日 Java 我要评论
手动给spring加入监听任务1、先写1个线程类,在springboot启动加载完,自动执行的操作放在里面@componentpublic class stepexecutor implements

手动给spring加入监听任务

1、先写1个线程类,在springboot启动加载完,自动执行的操作放在里面

@component
public class stepexecutor implements runnable {
    @override
    public void run() {
        startstreamtask();
 
    }
    /**
     * 项目启动后打开1个页面
     */
    public void startstreamtask() {
        try {
            runtime.getruntime().exec("cmd   /c   start   http://localhost:8080/index");
        } catch (exception ex) {
            ex.printstacktrace();
        }
    }
}

2、写1个监听器,监听项目加载完后执行指定操作

public class applicationstartup implements applicationlistener<contextrefreshedevent> {
    @override
    public void onapplicationevent(contextrefreshedevent event) {
        applicationcontext ac = event.getapplicationcontext();
        stepexecutor stepexecutor = ac.getbean(stepexecutor .class);
        thread thread = new thread(stepexecutor);
        thread.start();
    }
}

3、给springboot的启动类添加监听任务

@springbootapplication
public class speechapplication {
 
    public static void main(string[] args) {
        springapplication springapplication = new springapplication(speechapplication .class);
        springapplication.addlisteners(new applicationstartup());
        springapplication.run(args);
    }
}

spring容器加载完自动监听

1、实现springboot默认的监听接口,该方法在spring容器加载完自动监听

import org.springframework.beans.factory.annotation.value;
import org.springframework.boot.commandlinerunner;
import org.springframework.stereotype.component;


/**
 * 配置自动启动浏览器
 */

@component
public class mycommandrunner implements commandlinerunner {

    @value("${server.port}")
    private string port;

    @override
    public void run(string... args) {
        try {
            runtime.getruntime().exec("cmd   /c   start   http://localhost:" + port + "/index");
        } catch (exception ex) {
            ex.printstacktrace();
        }
    }
}

2、正常启动

@enablewebmvc
@springbootapplication
public class photoshowapplication {

    public static void main(string[] args) {
        springapplication.run(photoshowapplication.class, args);
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com