毕设20200529 Spring Boot 1 Spring Boot 2设置默认首页的正确姿势(三种方法) - 如何访问localhost:8080直接打开swagger-ui界面

※需要配置Swagger-ui,并使用Spring Boot 2的看官直接看方法2.2即可。

方法一:DefaultController实现

首先申明:这个方法适合自己项目里面带的index页面使用,不适合swagger-ui.html使用(跳转不过去,也显示不了内容,亲测)

@Controller
@RequestMapping("/")
public class DefaultController {
    @RequestMapping("/")
    public String index()  {
        return "forward:index.html";
    }
}

方法二:使用SpringDefaultView实现

2.1 Spring老版本中的写法

代码如下:

@Configuration
public class DefaultView extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:swagger-ui.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }
}

2.2 Spring5中的正确姿势

我们可以看到继承的WebMvcConfigurerAdapter已经过时(或不推荐使用),用@Deprecated标注了
在这里插入图片描述
查看它的源码发现:

/**
 * An implementation of {@link WebMvcConfigurer} with empty methods allowing
 * subclasses to override only the methods they're interested in.
 *
 * @author Rossen Stoyanchev
 * @since 3.1
 * @deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made
 * possible by a Java 8 baseline) and can be implemented directly without the
 * need for this adapter
 */
@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {

翻译:在Spring5.0 中WebMvcConfigurer有默认的方法(Java8使之成为可能),可以直接被implements而不需要用这个类了。

代码如下:

@Configuration
public class DefaultView implements WebMvcConfigurer {

    /**
     * Configure simple automated controllers pre-configured with the response
     * status code and/or a view to render the response body. This is useful in
     * cases where there is no need for custom controller logic -- e.g. render a
     * home page, perform simple site URL redirects, return a 404 status with
     * HTML content, a 204 with no content, and more.
     */
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/","swagger-ui.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }
}

方法三:Windows中配置监听事件直接打开Swagger界面(亲测仅适用于Windows)

代码如下:

@Configuration
public class XxxApplication {

    @EventListener({ApplicationReadyEvent.class})
    public void ready() {
        System.out.println("Application is almost started ... opening the browser");
        //Homepage URL link here
        String url = "http://localhost:"+ port + File.separator +"swagger-ui.html";
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

其中port最好在application.properties里面配置。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章