java dubbo swagger_springboot dubbo resteasy 简易集成swagger

之前在springmvc中集成swagger,轻松加愉快,整套springfox进来,ui加api都有了。

现在的新项目,采用了springboot + dubbo + resteasy直出restful api的方式,轻便确实轻便,但是不如springmvc的资料多。不过,也让我在使用中,增加了更多的机会去了解底层。

翻了下swagger的文档,他是已经支持了resteasy了。于是拿来了他的demo看看,确实很方便,直接就能出api。几乎是0代码集成。他是使用servlet方式集成进去的。但是我的springboot,不支持在嵌入式servlet下用spi增加servlet。

所以我最后选用了直接添加service的方式。

首先增加一个config bean,创建一个openapicontext。后续可以用这个来得到swagger内容

@Configuration

public class SwaggerConfig {

@Bean

public OpenApiContext openApiContext(){

Set> resources = new LinkedHashSet();

// 仅抓取有tag注解的路径

Set beanList = SpringContextUtils.getClassSetOfAnnotation(Tag.class);

resources.addAll(beanList);

OpenApiContext openApiContext = null;

if (!resources.isEmpty()) {

// init context

try {

SwaggerConfiguration oasConfig = new SwaggerConfiguration()

.resourceClasses(resources.stream().map(c -> c.getName()).collect(Collectors.toSet()));

openApiContext = new JaxrsOpenApiContextBuilder()

.openApiConfiguration(oasConfig)

.buildContext(true);

} catch (OpenApiConfigurationException e) {

throw new RuntimeException(e.getMessage(), e);

}

}

return openApiContext;

}

}

然后写一个service,把swagger文档当成json内容返回出去。

@Service(interfaceClass = SwaggerDocService.class)

@Path("swaggerdoc")

public class SwaggerDocServiceImpl implements SwaggerDocService {

@Autowired

OpenApiContext openApiContext; // 注入刚才的config bean

@Path("/all")

@GET

public String doc(){

boolean pretty = false; // json是否美化

OpenAPI oas = openApiContext.read(); // oas里面包含了所有的文档内容

try {

// 格式化oas的内容

String result = pretty ? Json.pretty(oas) : Json.mapper().writeValueAsString(oas);

return result;

} catch (JsonProcessingException e) {

e.printStackTrace();

}

return "";

}

}

搞定,现在访问 127.0.0.1/swaggerdoc/all,就出来了。

想要来个ui?访问这里 http://petstore.swagger.io,里面贴上上面的地址,完美。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值