2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spring Boot context が立ち上がったら自動的にブラウザを開く / Open browser for spring-boot

Last updated at Posted at 2017-04-23

エンジニアじゃ無い人向けのツールを、ローカルで起動できる Jar + 実際の操作は Web 経由、でやろうと思ったときに。

ポート8080固定→ 困りそう
ポート任意→ ログからポート見つけてブラウザ開くとか無理そう

なので、上手く自動割り当て済みのポートでブラウザ勝手に開く方法無いかと探していた。

以下の用にして解決。

BrowserStartupSupport.java

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;

import org.springframework.boot.context.embedded.EmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

@Service
public class BrowserStartupSupport {
    @EventListener
    public void openBrowserOnServletContainerInitialized(
            final EmbeddedServletContainerInitializedEvent event) throws IOException {
        final EmbeddedServletContainer embeddedServletContainer = event.getEmbeddedServletContainer();
        final int port;

        if (embeddedServletContainer instanceof TomcatEmbeddedServletContainer) {
            port = ((TomcatEmbeddedServletContainer) embeddedServletContainer)
                    .getTomcat().getConnector().getPort();
        } else {
            port = embeddedServletContainer.getPort(); // Maybe
        }

        Desktop desktop = Desktop.getDesktop();
        desktop.browse(URI.create("http://localhost:" + port));
    }
}

これを、

application.yml
server.port: 0 # Search random available port.

と組み合わせて使うと、実行時に空いてるポートで Tomcat 起動&ブラウザでその画面が開く。

参考

2
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?