IDEA開發環境中,SpringMVC與Swagger2的整合。完成restful風格的API開發
阿新 • • 發佈:2019-02-12
專案結構
Swapper2在POM中的依賴
<!-- springfox依賴 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox.version}</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>15.0</version></dependency>
建立SwaggerConfig類
注意這裡:這裡掃描的是controller@ComponentScan(basePackages = {"com.mano233.ssm.controller"})
.apis(RequestHandlerSelectors.basePackage("com.mano233.ssm.controller")).build();
在Spring配置中新增bean和靜態資源訪問
因為Swapper2.*版本將靜態資源全部整合到了jar中,
所以要在springmvc的xml配置中新增如下內容
<!--這裡是自定義的swapper2配置--> <bean class="com.mano233.ssm.swagger2.SwaggerConfig" id="swagger2Config"/> <!--當然你也可以使用預設的swagger2配置--> <!--<bean class="springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration" id="swagger2Config"/>--> <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/> <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/> <mvc:default-servlet-handler/>
在controller中添加註解
在瀏覽器中訪問
訪問localhost:80080/專案名/swagger-ui.html
大功告成!
注意事項:
尤其注意一下自己專案在tomcat中的名字,
不知道是不是BUG,博主改成MyspringSSM這個名字之後就無法訪問localhost:80080/專案名/swagger-ui.html了。。。。。很尷尬的問題,而且網上的方法基本不管用了,博主也是被坑了很久,知道換了個名字
囧