springmvc整合swagger2.x

1、新增swagger依赖

        <!-- swagger -->  
        <dependency>  
            <groupId>io.springfox</groupId>  
            <artifactId>springfox-swagger2</artifactId>  
            <version>2.9.2</version>  
        </dependency>  
        <dependency>  
            <groupId>io.springfox</groupId>  
            <artifactId>springfox-swagger-ui</artifactId>  
            <version>2.9.2</version>  
        </dependency>

2、新增swagger配置类

@Configuration //声明该类为配置类
@EnableSwagger2 //声明启动Swagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage(“com.demo.controller”))
                .paths(PathSelectors.any())
                .build();
    }

}

3、修改spring配置

修改包扫描配置

<context:component-scan base-package="com.demo.controller">
    <!-- 把Controller、RestController 的注解排除掉,在spring-mvc.xml单独扫描Controller注解 -->
    <context:exclude-filter type="annotation"  expression="org.springframework.stereotype.Controller" />
    <context:exclude-filter type="annotation"  expression="org.springframework.web.bind.annotation.RestController" />
    
    <!--由于controller在spring-mvc配置中加载,然后swagger也要在mvc中加载才能扫描到controller,所以不需要在spring加载-->
    <context:exclude-filter type="regex" expression="com.demo.config.SwaggerConfig"/>
    
</context:component-scan>

4、修改spring-mvc配置

4.1、修改包扫描配置

<context:component-scan base-package="com.demo" use-default-filters="false">
    <context:include-filter type="annotation"  expression="org.springframework.stereotype.Controller" />
    <context:include-filter type="annotation"  expression="org.springframework.web.bind.annotation.RestController" />
    <!--加载swagger配置类-->
    <context:exclude-filter type="regex" expression="com.demo.config.SwaggerConfig"/>
</context:component-scan>

4.2、增加swagger相关配置

   <!-- swagger -->
   <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
   <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/> 

参考文章:

https://blog.csdn.net/jakekong/article/details/112346392
https://blog.csdn.net/lovelichao12/article/details/79387569

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值