spring boot(三)自定义启动器 swagger2

上回咋们说到,spring boot 的web开发,使用swagger作为接口测试工具,不知道大家又没有发现一个小问题,就是swagger需要在config类中配置一个Docket bean,还要引入相对的jar包,那每次构建web项目都需要这些重新再写一次?不用,spring boot启动器是用来干什么的,不就是自动集成么,现在我们就来自定义一个swagger的启动器。

启动器

第一回咋们说道,spring boot starter实现的一个核心是啥,spring.factories嘛。首先新建一个swagger-spring-boot-starter maven项目。

xxx-spring-boot-starter是spring boot的建议命名规则,为了和官方的spring-boot-starter-xxx做区分。

项目已经有了,开始撸。。。

创建swagger config配置项

@ConfigurationProperties(prefix = "spring.swagger") //创建配置项,并读取文件以spring.swagger开头的配置参数
@ConditionalOnWebApplication //在web环境下创建此项配置
@EnableSwagger2
public class swagger {

    private String basePackage;
    private String title;
    private String version;

    [@Bean](https://my.oschina.net/bean)
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title(title)
                .version(version)
                .build();
    }

    public void setBasePackage(String basePackage) {
        this.basePackage = basePackage;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}

在resources目录下创建META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.le.swagger

然后打包,在我们的web项目中去掉关于swagger的引入,并重新引入我们的swagger-spring-boot-starter包

	<dependency>
            <groupId>cn.le</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

然后在web项目中的配置文件中加入我们swagger-spring-boot-starter的配置参数

spring.swagger.basePackage=cn.le
#只能识别unicode码
spring.swagger.title=\u81ea\u5b9a\u4e49\u0073\u0077\u0061\u0067\u0067\u0065\u0072\u0020\u0073\u0074\u0061\u0072\u0074\u0065\u0072
spring.swagger=1.0

然后启动项目,访问swagger-ui.html

搞定,是不是很简单。

-------代码 git 地址 https://gitee.com/distant/spring-boot-geit.git

转载于:https://my.oschina.net/u/2258281/blog/3033185

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值