首先,添加mvc框架(略)以及Swagger Maven依赖:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.4</version> </dependency>
1> 配置servler-mvc.xml:
<mvc:annotation-driven/> <mvc:default-servlet-handler/> <!-- 开启注解扫描,用来扫描拥有swagger注解的handler --> <context:component-scan base-package="com.bingco.controller" /> <!-- 扫描注解configuration,这里配置了只扫描路径包下的类 --> <context:component-scan base-package="com.bingco" resource-pattern="SwaggerConfig.class" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/templates/"/> <property name="suffix" value=".ftl"/>
</bean> <!-- 这是 Swagger UI Maven 中的资源,做好映射 --> <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/> <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
2> 创建类SwaggerConfig:
@Configuration // 必须存在 // @EnableWebMvc 用来启用MVC配置的,主要在Spring boot中使用,这个demo是配置式的,用不着 @EnableSwagger2 // 必须存在 @ComponentScan(basePackages = {"com.bingco.controller"}) // 不是必须,可以在配置文件中开启扫描 public class SwaggerConfig { @Bean public Docket customDocket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()); } private ApiInfo apiInfo() { Contact contact = new Contact("小明", "http://www.cnblogs.com/getupmorning/", "zhaoming0018@126.com"); // 相当于明信片 return new ApiInfoBuilder() .title("前台API接口") // 标题 .description("前台API接口") // 描述 .contact(contact) .version("1.1.0") // 版本 .build(); } }
访问项目:http://127.0.0.1:80/swagger-ui.html (提示:如果访问时有弹窗提示url问题的,可以把IP换成localhost)
-- over --