如何使用swwger与dropwizard .0.7.0

时间:2014-04-25 19:04:01

标签: swagger dropwizard

我有最新的dropwizard设置。现在我创建了一个简单的API,我试图在上面添加Swagger。有一个用于dropwizard的Swagger实现,但示例代码是针对Yammer dropwizard 0.6.2,它需要addProvider和addResource。 io.dropwizard环境似乎没有这个功能。你可以告诉我如何在io.dropwizard下做到这一点吗?

4 个答案:

答案 0 :(得分:9)

对于Dropwizard 0.7.0我像这样配置招摇:

void configureSwagger(Environment environment) {
  environment.jersey().register(new ApiListingResourceJSON());
  environment.jersey().register(new ApiDeclarationProvider());
  environment.jersey().register(new ResourceListingProvider());
  ScannerFactory.setScanner(new DefaultJaxrsScanner());
  ClassReaders.setReader(new DefaultJaxrsApiReader());
  SwaggerConfig config = ConfigFactory.config();
  config.setApiVersion(API_VERSION);
  config.setBasePath(".." + environment.getApplicationContext().getContextPath());
}

修改

使用Dropwizard运行Swagger UI克隆repo并将dist目录复制到src/main/resources/swagger/(根据需要自定义)。然后像这样添加资产包:

@Override
public void initialize(Bootstrap<ApplicationConfiguration> bootstrap) {
  bootstrap.addBundle(new AssetsBundle("/swagger/", "/docs", "index.html"));
}

答案 1 :(得分:2)

您可以在此处看到Swagger规范2.0的一些更改:

https://github.com/swagger-api/swagger-core/tree/develop_2.0/samples/java-dropwizard

即配置略有不同:

  @Override
  public void run(SwaggerSampleConfiguration configuration, Environment environment) {
    environment.jersey().register(new ApiListingResource());

    // specific to the sample
    environment.jersey().register(new PetResource());
    environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
    BeanConfig config = new BeanConfig();

    // api specific configuration
    config.setTitle("Swagger sample app");
    config.setVersion("1.0.0");
    config.setResourcePackage("com.wordnik.swagger.sample");
    config.setScan(true);
  }

答案 2 :(得分:1)

Dropwizard 1.0.2,Swagger 1.5.0。从您的应用程序run()中调用此方法。

private void configureSwagger(Environment environment) {
    BeanConfig magicBean = new BeanConfig();
    magicBean.setVersion("0.1");
    magicBean.setTitle("title");
    magicBean.setBasePath("/api");
    magicBean.setResourcePackage("com.me.resources");
    magicBean.setScan(true);
    environment.jersey().register(new ApiListingResourceJSON());
    environment.jersey().register(new SwaggerSerializers());
}

答案 3 :(得分:0)

除了上面提到的@fehguy消息之外,我还想补充一下如何在dropwizard中实际获取基本路径(至少为0.8),因为显然你无法从yml中获取basePath,如下所示:

config.setBasePath(".." + environment.getApplicationContext().getContextPath());

你必须做这样的事情:

DefaultServerFactory defaultServerFactory = (DefaultServerFactory) serverConfiguration.getServerFactory();
String basePath = defaultServerFactory.getApplicationContextPath();

请参阅github问题here,我花了很多时间才弄明白。希望这有助于其他人