1

I have a Spring boot java 23 web api using maven.

In my pom.xml I am using springdoc-openapi v2.8.8:

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
  <version>2.8.8</version>
</dependency>

Everything works fine and when i open up http://localhost:8080/swagger-ui.html I can see the swaggerpage.

What I wanted now is that the swaggerpage opens automatically when I start the Service.

So I added a BrowserLauncherConfig

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

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

@Configuration
public class BrowserLauncherConfig {

    private final Environment environment;

    public BrowserLauncherConfig(Environment environment) {
        this.environment = environment;
    }

    @Bean
    public CommandLineRunner openBrowser() {
        return _ -> {
            try {
                String port = environment.getProperty("server.port", "8080");
                String urlString = "http://localhost:" + port + "/swagger-ui.html";
                URI uri = new URI(urlString);

                if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
                    Desktop.getDesktop().browse(uri);
                } else {
                    Runtime runtime = Runtime.getRuntime();
                    String os = System.getProperty("os.name").toLowerCase();
                    if (os.contains("win")) {
                        runtime.exec(new String[]{"rundll32", "url.dll,FileProtocolHandler", uri.toString()});
                    } else if (os.contains("mac")) {
                        runtime.exec(new String[]{"open", uri.toString()});
                    } else if (os.contains("nix") || os.contains("nux")) {
                        runtime.exec(new String[]{"xdg-open", uri.toString()});
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
    }
}

My problem here is that when I develop and make changes on the Service in VS Code, everytime I make a change and save, the browser pops up and opens the swaggerpage because of hot reload.

I wonder if there is a better solution for this than using the BrowserLauncherConfig

I dont want do use localstorage or config file.

Just a straight forward check if the swaggerpage is already open.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.