java 如何将 swagger 与球衣 + spring-boot 结合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35966204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to integrate swagger with jersey + spring-boot
提问by Joey Yi Zhao
I am using springboot + jersey for web restful implementation. Now I am going to integrate swagger into our application. I did following.
我正在使用 springboot + jersey 进行 web restful 实现。现在我要将 swagger 集成到我们的应用程序中。我做了以下。
@Configuration
@EnableSwagger2
public class JerseyConfiguration extends ResourceConfig {
public JerseyConfiguration(){
register(HelloworldAPI.class);
configureSwagger();
}
private void configureSwagger() {
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion("1.0.2");
beanConfig.setSchemes(new String[]{"http"});
beanConfig.setHost("localhost:8080");
beanConfig.setBasePath("/");
beanConfig.setResourcePackage("com.cooltoo.api");
beanConfig.setPrettyPrint(true);
beanConfig.setScan(true);
}
}
I added following dependences on build.gradle:
我添加了以下对 build.gradle 的依赖:
compile('io.springfox:springfox-swagger2:'+springfoxSwaggerVersion)
compile('io.springfox:springfox-petstore:'+springfoxSwaggerVersion)
compile('io.springfox:springfox-swagger-ui:'+springfoxSwaggerVersion)
compile('io.swagger:swagger-jersey2-jaxrs:1.5.8')
I was able to launch the web application but I wander which url is for swagger? I tried with http://localhost:8080, http://localhost:8080/swagger, and http://localhost:8080/swagger-ui.html. But none of them could be accessed.
我能够启动 web 应用程序,但我徘徊哪个 url 是为了 swagger?我尝试使用http://localhost:8080、http://localhost:8080/swagger和http://localhost:8080/swagger-ui.html。但是没有一个可以访问。
回答by ootero
I think @EnableSwagger2
annotation and springfox
dependencies would work if the endpoints are implemented using Spring MVC instead of a JAX-RS implementation.
我认为如果使用 Spring MVC 而不是 JAX-RS 实现来实现端点,则@EnableSwagger2
注释和springfox
依赖项会起作用。
I blogged about this a few months ago, Microservices using Spring Boot, Jersey Swagger and Docker
几个月前我写了一篇关于这个的博客,使用 Spring Boot、Jersey Swagger 和 Docker 的微服务
Basically if you need to document your Jersey-implemented endpoints, you would need to:
基本上,如果您需要记录 Jersey 实现的端点,则需要:
1) Make sure your Spring Boot app scans for components located in specific packages (ie com.asimio.jerseyexample.config) via:
1) 确保您的 Spring Boot 应用程序通过以下方式扫描位于特定包(即 com.asimio.jerseyexample.config)中的组件:
@SpringBootApplication(
scanBasePackages = {
"com.asimio.jerseyexample.config", "com.asimio.jerseyexample.rest"
}
)
2) Jersey configuration class implementation:
2) Jersey 配置类实现:
package com.asimio.jerseyexample.config;
...
@Component
public class JerseyConfig extends ResourceConfig {
@Value("${spring.jersey.application-path:/}")
private String apiPath;
public JerseyConfig() {
// Register endpoints, providers, ...
this.registerEndpoints();
}
@PostConstruct
public void init() {
// Register components where DI is needed
this.configureSwagger();
}
private void registerEndpoints() {
this.register(HelloResource.class);
// Access through /<Jersey's servlet path>/application.wadl
this.register(WadlResource.class);
}
private void configureSwagger() {
// Available at localhost:port/swagger.json
this.register(ApiListingResource.class);
this.register(SwaggerSerializers.class);
BeanConfig config = new BeanConfig();
config.setConfigId("springboot-jersey-swagger-docker-example");
config.setTitle("Spring Boot + Jersey + Swagger + Docker Example");
config.setVersion("v1");
config.setContact("Orlando L Otero");
config.setSchemes(new String[] { "http", "https" });
config.setBasePath(this.apiPath);
config.setResourcePackage("com.asimio.jerseyexample.rest.v1");
config.setPrettyPrint(true);
config.setScan(true);
}
}
3) Resource implementation using JAX-RS (Jersey) and Swagger annotations:
3)使用JAX-RS(Jersey)和Swagger注解的资源实现:
package com.asimio.jerseyexample.rest.v1;
...
@Component
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Api(value = "Hello resource", produces = "application/json")
public class HelloResource {
private static final Logger LOGGER = LoggerFactory.getLogger(HelloResource.class);
@GET
@Path("v1/hello/{name}")
@ApiOperation(value = "Gets a hello resource. Version 1 - (version in URL)", response = Hello.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Hello resource found"),
@ApiResponse(code = 404, message = "Hello resource not found")
})
public Response getHelloVersionInUrl(@ApiParam @PathParam("name") String name) {
LOGGER.info("getHelloVersionInUrl() v1");
return this.getHello(name, "Version 1 - passed in URL");
}
...
}
4) Make sure your app's Spring Boot configuration file makes a distinction between Spring MVC (for actuator endpoints) and Jersey (for resources) endpoints:
4) 确保您的应用程序的 Spring Boot 配置文件区分 Spring MVC(用于执行器端点)和 Jersey(用于资源)端点:
application.yml
应用程序.yml
...
# Spring MVC dispatcher servlet path. Needs to be different than Jersey's to enable/disable Actuator endpoints access (/info, /health, ...)
server.servlet-path: /
# Jersey dispatcher servlet
spring.jersey.application-path: /api
...
回答by Sanjay-Dev
I would Suggest to Use Simply Swagger Jersey JAXRS dependency and start . Using Swagger With Spring Boot is fairly easy but when it comes to using with Jersey , it can be tricky.
我建议使用简单的 Swagger Jersey JAXRS 依赖项并开始 . 将 Swagger 与 Spring Boot 一起使用相当容易,但在与 Jersey 一起使用时,它可能会很棘手。
First Thing that we need to do is Configure Swagger to Use with Jersey and update your Jersey Config like below.
我们需要做的第一件事是配置 Swagger 以与 Jersey 一起使用,并像下面这样更新您的 Jersey 配置。
Jersey Config is the Place where we need to do All Configurations
Jersey Config 是我们需要做所有配置的地方
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import javax.annotation.PostConstruct;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@ApplicationPath("/api")
public class JerseyConfig extends ResourceConfig {
@Autowired
public JerseyConfig(ObjectMapper objectMapper) {
packages("com.rest.resources");
// u can also specify resource class names like below
//register(UserResource.class)
//register(AdminResource.class)
}
@PostConstruct
public void init() {
// Register components where DI is needed
this.SwaggerConfig();
}
private void SwaggerConfig() {
this.register(ApiListingResource.class);
this.register(SwaggerSerializers.class);
BeanConfig swaggerConfigBean = new BeanConfig();
swaggerConfigBean.setConfigId("Swagger Jersey Example");
swaggerConfigBean.setTitle("Using Swagger ,Jersey And Spring Boot ");
swaggerConfigBean.setVersion("v1");
swaggerConfigBean.setContact("DeveloperName");
swaggerConfigBean.setSchemes(new String[] { "http", "https" });
swaggerConfigBean.setBasePath("/api");
swaggerConfigBean.setResourcePackage("com.rest.resources");
swaggerConfigBean.setPrettyPrint(true);
swaggerConfigBean.setScan(true);
}
Now that we have done all configurations, we need to verify that swagger.json is generated successfully or not . This is an important step , verify following URL .
现在我们已经完成了所有的配置,我们需要验证 swagger.json 是否生成成功。这是重要的一步,验证以下 URL。
http://localhost:PORT/baseContext/api/swagger.json
As we have given @Application Path as "/api" and we have not configured any context so our base context is "/".Hence We visit url as http://localhost:8080/api/swagger.json.
由于我们将@Application Path 指定为“/api”并且我们还没有配置任何上下文,因此我们的基本上下文是“/”。因此我们访问 url 为 http://localhost:8080/api/swagger.json。
Now that our swagger.json is loaded we now need to configure Swagger UI . Its just like a Static HTML or resource access in a simple web app.
现在我们的 swagger.json 已加载,我们现在需要配置 Swagger UI。它就像一个简单的 Web 应用程序中的静态 HTML 或资源访问。
If you are not sure how to configure, please visit this articlewhich says how to load swagger-UIat the end of the article.
如果您不确定如何配置,请访问本文末尾说明如何加载swagger-UI的文章。
回答by Maxim Votyakov
Maybe you use rather old version of springfox, but now (for version 2.4.0) it must be configured very different from your code, see http://springfox.github.io/springfox/docs/current/
也许您使用的是相当旧版本的 springfox,但现在(对于版本 2.4.0)它必须与您的代码配置非常不同,请参阅http://springfox.github.io/springfox/docs/current/
For example, I have the following springfox configuration:
例如,我有以下 springfox 配置:
@Configuration
@EnableSwagger2
class SwaggerConfig {
@Bean
Docket rsApi() {
new Docket(DocumentationType.SWAGGER_12)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage('com.test.service'))
.paths(PathSelectors.any())
.build()
.pathMapping('/')
.useDefaultResponseMessages(false)
}
private ApiInfo apiInfo() {
new ApiInfoBuilder()
.title('Test API')
.description('Test API')
.version('0.0.10.SNAPSHOT')
.termsOfServiceUrl('')
.contact('Test company')
.license('Public')
.licenseUrl('http://example.com/')
.build()
}
}