自定义spring boot starter

1.需求

在我们学习SpringBoot时都已经了解到starter是SpringBoot的核心组成部分,在实际业务开发过程中,会遇到各组件都需要引用公共配置的需求,以前的做法都是且手动通过@Bean注解来引入,如果有很多组件需要引用就好带来额外的工作量。spring boot starter 给我们提供了一种思路,即只需在pom.xml引入对应的starter jar包即可,无需手动一个个注入。

2.构建自定义starter

本文以创建一个swagger starter为demo。

2.1 创建maven项目

pom.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>kaven-cloud</artifactId>
        <groupId>com.github.kaven</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>swagger-spring-boot-starter</artifactId>
    <name>Swagger Boot Starter</name>
    <description>自定义swagger starter</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
        </dependency>
    </dependencies>
</project>

PS:我们这个starter并不做其他复杂逻辑的编写,所以这里的依赖只是添加了spring-boot-autoconfigure,swagger相关jar。
其中spring boot选用的是1.5.12版本。

2.2配置映射参数实体

SpringBoot提供了一个注解@ConfigurationProperties,该注解可以完成将application.yml/application.properties配置文件内的有规则的配置参数映射到实体内的field内。

 

package com.github.kaven.swagger.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
 * swagger 配置项
 * Created by Kaven
 * Date: 2018/5/7
 */
@Configuration
@ConfigurationProperties(prefix = "kaven.swagger",ignoreUnknownFields = false)
public class SwaggerProperties {
    private String title = "Application API";
    private String description = "API documentation";
    private String version = "0.0.1";
    //swagger 开关
    private boolean enabled = false;
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
    public boolean isEnabled() {
        return enabled;
    }
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}

PS:配置项不可缺少@Configuration,自行查官方文档。

2.3实现自动化配置

该步骤解决手动@Bean注入

 

package com.github.kaven.swagger.config;

import com.github.kaven.swagger.properties.SwaggerProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.util.StopWatch;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * swagger 配置类
 * Created by Kaven
 * Date: 2018/5/7
 * Desc:
 */

@Configuration
@EnableConfigurationProperties(SwaggerConfig.class)
@ConditionalOnClass({ApiInfo.class})
@EnableSwagger2
@Profile("swagger")
public class SwaggerConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(SwaggerConfig.class);

    @Autowired
    SwaggerProperties swaggerProperties;

    @Bean
    public Docket createRestApi() {

        LOGGER.info("---starting swagger -----");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        ApiInfo apiInfo = new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .version(swaggerProperties.getVersion())
                .build();

        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();

        stopWatch.stop();
        LOGGER.info("-----end swagger documentation----{} seconds",stopWatch.getTotalTimeSeconds());
        return docket;
    }

}

PS:注解说明
@EnableConfigurationProperties:这是一个开启使用配置参数的注解,value值就是我们配置实体参数映射的ClassType,将配置实体作为配置来源。

SpringBoot内置条件注解

有关@ConditionalOnXxx相关的注解这里要系统的说下,因为这个是我们配置的关键,根据名称我们可以理解为具有Xxx条件,当然它实际的意义也是如此,条件注解是一个系列,下面我们详细做出解释

@ConditionalOnBean:当SpringIoc容器内存在指定Bean的条件
@ConditionalOnClass:当SpringIoc容器内存在指定Class的条件
@ConditionalOnExpression:基于SpEL表达式作为判断条件
@ConditionalOnJava:基于JVM版本作为判断条件
@ConditionalOnJndi:在JNDI存在时查找指定的位置
@ConditionalOnMissingBean:当SpringIoc容器内不存在指定Bean的条件
@ConditionalOnMissingClass:当SpringIoc容器内不存在指定Class的条件
@ConditionalOnNotWebApplication:当前项目不是Web项目的条件
@ConditionalOnProperty:指定的属性是否有指定的值
@ConditionalOnResource:类路径是否有指定的值
@ConditionalOnSingleCandidate:当指定Bean在SpringIoc容器内只有一个,或者虽然有多个但是指定首选的Bean
@ConditionalOnWebApplication:当前项目是Web项目的条件

2.4自定义spring.factories

我们在src/main/resource目录下创建META-INF目录,并在目录内添加文件spring.factories,具体内容如下所示:

 

#配置自定义Starter的自动化配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.github.kaven.swagger.config.SwaggerConfig

PS:可以看到配置的结构形式是Key=>Value形式,多个Value时使用,隔开,那我们在自定义starter内也可以使用这种形式来完成,我们的目的是为了完成自动化配置,所以我们这里Key则是需要使用org.springframework.boot.autoconfigure.EnableAutoConfiguration

3.创建测试SpringBoot项目

业务组件引入swagger-spring-boot-starter.jar

 <dependency>
          <groupId>com.github.kaven</groupId>
          <artifactId>swagger-spring-boot-starter</artifactId>
         <version>1.0-SNAPSHOT</version>
  </dependency>

application.properties配置项

kaven.swagger.title=wangwei api 
kaven.swagger.description=9999
kaven.swagger.version=1.0.0
kaven.swagger.enabled=true

spring.profiles.active=swagger

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值