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,里面贴上上面的地址,完美。

你可能感兴趣的:(Java,swagger,resteasy,springboot)