一.Swagger介紹
百度百科:Swagger的目標是為REST APIs 定義一個標准的,與語言無關的接口,使人和計算機在看不到源碼或者看不到文檔或者不能通過網絡流量檢測的情況下能發現和理解各種服務的功能。當服務通過Swagger定義,消費者就能與遠程的服務互動通過少量的實現邏輯。類似於低級編程接口,Swagger去掉了調用服務時的很多猜測。
我覺得把Swagger當成一種開發工具就好,省去了手寫文檔的步驟,生成文檔並能測試,注解的方式讓其他人看代碼也更加清楚方便。
想了解更多有關資料點擊: Swagger官網
瀏覽 Swagger-Spec去了解更多關於Swagger 項目的信息,包括附加的支持其他語言的庫。
二.搭建
<!--使用Swagger2構建RESTful API文檔-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
三.案例
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
*
* @return ApiInfo
*/
ApiInfo apiInfo() {
return new ApiInfoBuilder().title("XXX API").description("XXX原子服務")
.termsOfServiceUrl("").version("1.0.0").contact(new Contact("", "", "")).build();
}
/**
* Bean. 〈一句話功能簡述〉 〈功能詳細描述〉
*
* @return XXX
*/
@Bean
public Docket mktConfigImplementation() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)).build()
.directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class).apiInfo(apiInfo());
}
}
這里只添加了一些文檔接口的配置,考慮到主方法入口還可能搭配其它注解使用,例如Feign,redisTemplate,事務注解,需要讀者單獨完成,舉個栗子吧:
@EnableTransactionManagement #申明事務注解的,(Spring Boot 使用事務非常簡單,首先使用注解 @EnableTransactionManagement 開啟事務支持后,然后在訪問數據庫的Service方法上添加注解 @Transactional 便可。)
@SpringBootApplication #入口類,使用main方法即可啟動SpringBoot項目
@EnableDiscoveryClient # @EnableDiscoveryClient和@EnableEurekaClient共同點就是:能夠讓注冊中心發現,掃描到服務,不同點:@EEC只適用於Euraka作為注冊中心,@EDC可以是其它注冊中心
@ComponentScan(basePackages = "com.migu") #創建一個配置類,在配置類上添加 @ComponentScan 注解。該注解默認會掃描該類所在的包下所有的配置類,相當於之前的 <context:component-scan>。使用 ApplicationContext 的 getBeanDefinitionNames() 方法獲取已經注冊到容器中的 bean 的名稱
@EnableScheduling #開啟定時任務注解,后續使用在@Service中加入@Scheduled方法,即可定時發布任務
@EnableFeignClients #可理解為塞到注冊中心,實現FeginClient不同微服訪問
public class CmbsQueryOrderApplication {
/**
* <restTemplate>. <裝配一個全局單例RestTemplate Spring Bean用於負載均衡遠程調用>
*
* @return [返回類型說明]
* @exception/throws [違例類型] [違例說明]
* @author jianghao
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(CmbsQueryOrderApplication.class, args);
}
}