1.需求
在我們學習SpringBoot時都已經(jīng)了解到starter是SpringBoot的核心組成部分粗梭,在實際業(yè)務開發(fā)過程中争便,會遇到各組件都需要引用公共配置的需求级零,以前的做法都是且手動通過@Bean注解來引入,如果有很多組件需要引用就好帶來額外的工作量滞乙。spring boot starter 給我們提供了一種思路奏纪,即只需在pom.xml引入對應的starter jar包即可,無需手動一個個注入斩启。
2.構(gòu)建自定義starter
本文以創(chuàng)建一個swagger starter為demo序调。
2.1 創(chuàng)建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配置映射參數(shù)實體
SpringBoot提供了一個注解@ConfigurationProperties垄琐,該注解可以完成將application.yml/application.properties配置文件內(nèi)的有規(guī)則的配置參數(shù)映射到實體內(nèi)的field內(nèi)边酒。
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實現(xiàn)自動化配置
該步驟解決手動@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:這是一個開啟使用配置參數(shù)的注解墩朦,value值就是我們配置實體參數(shù)映射的ClassType,將配置實體作為配置來源翻擒。
SpringBoot內(nèi)置條件注解
有關@ConditionalOnXxx相關的注解這里要系統(tǒng)的說下氓涣,因為這個是我們配置的關鍵牛哺,根據(jù)名稱我們可以理解為具有Xxx條件,當然它實際的意義也是如此劳吠,條件注解是一個系列引润,下面我們詳細做出解釋
@ConditionalOnBean:當SpringIoc容器內(nèi)存在指定Bean的條件
@ConditionalOnClass:當SpringIoc容器內(nèi)存在指定Class的條件
@ConditionalOnExpression:基于SpEL表達式作為判斷條件
@ConditionalOnJava:基于JVM版本作為判斷條件
@ConditionalOnJndi:在JNDI存在時查找指定的位置
@ConditionalOnMissingBean:當SpringIoc容器內(nèi)不存在指定Bean的條件
@ConditionalOnMissingClass:當SpringIoc容器內(nèi)不存在指定Class的條件
@ConditionalOnNotWebApplication:當前項目不是Web項目的條件
@ConditionalOnProperty:指定的屬性是否有指定的值
@ConditionalOnResource:類路徑是否有指定的值
@ConditionalOnSingleCandidate:當指定Bean在SpringIoc容器內(nèi)只有一個,或者雖然有多個但是指定首選的Bean
@ConditionalOnWebApplication:當前項目是Web項目的條件
2.4自定義spring.factories
我們在src/main/resource目錄下創(chuàng)建META-INF目錄痒玩,并在目錄內(nèi)添加文件spring.factories椰拒,具體內(nèi)容如下所示:
#配置自定義Starter的自動化配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.github.kaven.swagger.config.SwaggerConfig
PS:可以看到配置的結(jié)構(gòu)形式是Key=>Value形式,多個Value時使用,隔開凰荚,那我們在自定義starter內(nèi)也可以使用這種形式來完成燃观,我們的目的是為了完成自動化配置,所以我們這里Key則是需要使用org.springframework.boot.autoconfigure.EnableAutoConfiguration
3.創(chuàng)建測試SpringBoot項目
業(yè)務組件引入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