【发布时间】:2013-09-09 15:43:37
【问题描述】:
我正在努力实现 Swagger 以生成 API 文档。我在这里遵循配置指南:https://github.com/wordnik/swagger-core/wiki/Java-JAXRS-Quickstart,但它都是基于 XML 的,当我尝试执行我认为在运行时配置中等效的操作时,Grizzly 抱怨 - Cannot resolve method 'addServlet(java.lang.String, com.wordnik.swagger.jersey.config.JerseyJaxrsConfig)'。
似乎是JerseyJaxrsConfig extends HttpServlet 而不是Servlet。对我能做什么有什么建议吗?
public class Main {
public static final URI BASE_URI = getBaseURI();
public static final String API_VERSION = "0.1.0";
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost/").port(9998).build();
}
protected static HttpServer startServer() throws IOException {
ResourceConfig rc = new PackagesResourceConfig("com.my.package.api.resources", "com.wordnik.swagger.jersey.listing");
rc.getFeatures()
.put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
return GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
}
public static void main(String[] args) throws IOException {
//System.setProperty("java.util.logging.SimpleFormatter.format", "%4$s: %5$s%n");
System.setProperty("jsse.enableSNIExtension", "false"); //avoid unrecognized_name during SSL handshake with deconet
AnnotationConfigApplicationContext annotationCtx = new AnnotationConfigApplicationContext(Config.class);
//add API documentation
WebappContext ctx = new WebappContext("Documentation", "/docs");
ServletRegistration swaggerServletRegistration = ctx.addServlet("JerseyJaxrsConfig", new com.wordnik.swagger.jersey.config.JerseyJaxrsConfig());
swaggerServletRegistration.setInitParameter("api.version", API_VERSION);
swaggerServletRegistration.setInitParameter("swagger.api.basepath", BASE_URI.toString());
swaggerServletRegistration.setLoadOnStartup(2);
swaggerServletRegistration.addMapping("/*");
HttpServer httpServer = startServer();
System.out.println(String.format("Jersey app started with WADL available at " + "%sapplication.wadl\nHit enter to stop it...", BASE_URI, BASE_URI));
System.in.read();
httpServer.stop();
}
}
【问题讨论】:
-
HttpServlet 实现了 Servlet(通过 GenericServlet),所以应该不是问题。是编译时问题吗? IMO ServletRegistration swaggerServletRegistration = ctx.addServlet("JerseyJaxrsConfig", com.wordnik.swagger.jersey.config.JerseyJaxrsConfig.class);会是更好的等价物。
-
@alexey - 对,但问题是
JerseyJaxrsConfig extends Servlet而不是implement HttpServlet -
应该没问题。你能请。创建和共享测试用例(基于 maven 的项目会很棒)?