SpringCloud中使用Swagger API

一.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);
}
}


猜你喜欢

转载自www.cnblogs.com/liveinpresent/p/11639968.html