【Swagger2】integrate Swagger2 in Spring4 project
Description
Swagger is a powerful yet easy-to-use suite of API developer tools for teams and individuals, enabling development across the entire API lifecycle, from design and documentation, to test and deployment.
Environment & Tools
maven, Spring 4.1.6.RELEASE, SpringMVC 4.1.6.RELEASE, Swagger 2.7.0, jackson-databind 2.7.4,
Guide
import dependencies or jars
1 | <dependency> |
config Swagger2 in Java config
1 |
|
scan Swagger2 config to Spring IOC container
Add <context:component-scan base-package="--" />
in spring-mvc.xml
to scan the Swagger2 Config into Spring IOC container.
Modify --
to your package of SwaggerConfig
add resources mapping
Add resources mapping to the uri /swagger-ui.html
in spring-mvc.xml
.1
2<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
add a test controller
Add a test controller using only annotation of Spring1
2
3
4
5
6
7
8
9
10
11
"prototype") (
"/test") (
public class TestController {
"/hello", method = { RequestMethod.GET }) (value =
public AjaxJson hello() {
return new AjaxJson();
}
}
Add <context:component-scan base-package="--">
in spring-mvc.xml
to scan the controllers into Spring IOC container.
Modify --
to your package of TestController
access in browser
Access http://{ip}:{port}/{context_path}/swagger-ui.html
.
More
You can try more in SwaggerConfig and Swagger annotations.
global swagger config for api info
use swagger annotation
Summary
Spring4集成Swagger:真的只需要四步,五分钟速成
Most of my operations refer to the passage above.
In the first time, I did directly as it told, but I failed.
It could be the reason that I hadn’t scan the SwaggerConfig
into Spring IOC container because my project is an XML project totally based on XML configuration.
Actually, what we need to do is, 1.import dependencies, 2.enable SwaggerConfig, 3.add the SwaggerConfig and controllers to Spring IOC container
PS:
We use <context:component-scan base-package="--">
in spring-mvc.xml
to scan SwaggerConfig and controllers into Spring IOC container.
We use @EnableSwagger2
to build swagger-ui with all the controllers in Spring IOC container.
We can use .apis(RequestHandlerSelectors.basePackage("--"))
to build swagger-ui with specific controllers but only when they are in Spring IOC container.
Reference
Spring4集成Swagger:真的只需要四步,五分钟速成
13.9 SpringBoot集成Swagger2中遇到的问题
Other References
【springboot】springboot项目集成swagger的demo