文章目錄
※需要配置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裏面配置。