Spring Boot Swagger HTML 文档未显示 [英] Spring Boot Swagger HTML documentation is not getting displayed

查看:113
本文介绍了Spring Boot Swagger HTML 文档未显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring Boot 设置 REST API/微服务项目.我也在尝试启用 swagger 文档.当我运行 spring boot 应用程序时,我可以看到浏览到 localhost:8080/v2/api-docs 并返回 API 文档.但是,当我尝试浏览 http://localhost:8080/documentation/swagger-ui.htmlhttp://localhost:8080/swagger-ui.html 浏览器没有显示 swagger UI 文档.

I am setting up a REST API / Micro-services project using Spring Boot. I am also trying to enable swagger documentation. When I run spring boot application, I am able to see browse to the localhost:8080/v2/api-docs and it returns API documentation. However, when I attempt browsing http://localhost:8080/documentation/swagger-ui.html or http://localhost:8080/swagger-ui.html browser does not display swagger UI documentation.

我在 pom 文件中包含了以下依赖项以启用文档:

I have included following dependencies in the pom file to enable documentation :

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

此外,我创建了以下 swagger 配置类:

Also, I have create following swagger config class:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2);
    }
}

我在尝试访问时看到的响应 http://localhost:8080/servlet-context :

The response I am seeing when trying to access http://localhost:8080/servlet-context :

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Dec 21 03:16:26 GMT 2018
There was an unexpected error (type=Not Found, status=404).
No message available

服务器日志:

2018-12-21 03:25:14.294 DEBUG 4049 --- [  restartedMain] o.s.c.e.PropertySourcesPropertyResolver  : Found key 'spring.liveBeansView.mbeanDomain' in PropertySource 'systemProperties' with value of type String
2018-12-21 03:25:14.351  INFO 4049 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-12-21 03:25:14.355  INFO 4049 --- [  restartedMain] c.xxxx.springboot.demo.DemoApplication   : Started DemoApplication in 3.951 seconds (JVM running for 4.723)
2018-12-21 03:25:14.373 DEBUG 4049 --- [  restartedMain] o.s.boot.devtools.restart.Restarter      : Creating new Restarter for thread Thread[main,5,main]
2018-12-21 03:25:14.373 DEBUG 4049 --- [  restartedMain] o.s.boot.devtools.restart.Restarter      : Immediately restarting application
2018-12-21 03:25:14.373 DEBUG 4049 --- [  restartedMain] o.s.boot.devtools.restart.Restarter      : Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@1b3b349
2018-12-21 03:25:14.373 DEBUG 4049 --- [  restartedMain] o.s.boot.devtools.restart.Restarter      : Starting application com.xxxx.springboot.demo.DemoApplication with URLs [file:/Users/XXXXX/XXXXX/SpringMicroservices/SpringBoot/demo/target/classes/]
2018-12-21 03:25:14.763 DEBUG 4049 --- [on(2)-127.0.0.1] o.s.c.e.PropertySourcesPropertyResolver  : Found key 'local.server.port' in PropertySource 'server.ports' with value of type Integer
2018-12-21 03:25:14.995  INFO 4049 --- [on(2)-127.0.0.1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2018-12-21 03:25:14.995  INFO 4049 --- [on(2)-127.0.0.1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2018-12-21 03:25:14.995 DEBUG 4049 --- [on(2)-127.0.0.1] o.s.web.servlet.DispatcherServlet        : Detected StandardServletMultipartResolver
2018-12-21 03:25:14.995 DEBUG 4049 --- [on(2)-127.0.0.1] o.s.web.servlet.DispatcherServlet        : Detected AcceptHeaderLocaleResolver
2018-12-21 03:25:15.003 DEBUG 4049 --- [on(2)-127.0.0.1] o.s.web.servlet.DispatcherServlet        : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data

请在下面找到控制器之一:

Please find below one of the controllers:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;
import java.net.URI;
import java.util.List;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;

@RestController
public class UserResource {

    @Autowired
    private UserDaoService service;

    @GetMapping("/users")
    public List<User> retrieveAllUsers(){
        return service.findAll();
    }

    @GetMapping("/users/{id}")
    public Resource<User> retrieveUser(@PathVariable int id){
        User user = service.findOne(id);
        if(user==null)
            throw new UserNotFoundEception("id-" + id);

        Resource<User> resource = new Resource<User>(user);
        ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllUsers());
        resource.add(linkTo.withRel("all-users"));
        return resource;
    }

    @PostMapping("/users")
    public ResponseEntity<Object> CreateUser(@Valid @RequestBody User user){
        User savedUser = service.save(user);
        URI location = ServletUriComponentsBuilder
                .fromCurrentRequest().path("/{id}")
                .buildAndExpand(savedUser.getId())
                .toUri();

        return ResponseEntity.created(location).build();
    }

    @DeleteMapping("/users/{id}")
    public void deleteUser(@PathVariable int id){
        User user = service.deleteById(id);
        if(user==null)
            throw new UserNotFoundEception("id-" + id);
    }
}

推荐答案

package com.example.config

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.common.base.Predicate;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {


    public @Bean Docket restApi() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().paths(paths()).build();
    }

    /**
     * Url for documentation.
     * 
     * @return
     */
    private Predicate<String> paths() {
        return regex("/basepackage of your restcontroller/*");
    }

    /**
     * Description your application
     * 
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("App title").description("App description")
                .termsOfServiceUrl("").license("").licenseUrl("").version("1.0").build();
    }
}

这是一个控制器的例子:

Here is an example of controller :

@Api(value = "membre")
@RestController
public class ExampleControleur {

    @RequestMapping(value = "/find", method = RequestMethod.GET, produces = {
            MediaType.APPLICATION_JSON_VALUE }, consumes = { MediaType.APPLICATION_JSON_VALUE })
    @ApiOperation(httpMethod = "GET", value = "example text", notes = "note text ")
    @ResponseBody
    @ApiResponses(value = { @ApiResponse(code = 200, message = "OK !"),
            @ApiResponse(code = 422, message = "description."),
            @ApiResponse(code = 401, message = "description"), 
            @ApiResponse(code = 403, message = "description"),
            @ApiResponse(code = 404, message = "description"),
            @ApiResponse(code = 412, message = "description."),
            @ApiResponse(code = 500, message = "description.") })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params1", value = "description.", required = true, dataType = "string", paramType = "query", defaultValue = "op"),
            @ApiImplicitParam(name = "params2", value = "description.", required = true, dataType = "string", paramType = "query")})
    public ResponseEntity<MyObject> getObjet(@RequestParam(value = "params1", required = true) Params1 params1,
            @RequestParam(value = "params2", required = true) String param2){
            }

    }

您可以使用此类进行测试,但我想您已经在控制器中编写了所有 swagger 注释!

You can test with this class, but i suppose that you have written all the swagger annotations in your controllers !

你可以添加到你的主类 @ComponentScan(basePackages={"the package of your config swagger class"})

You can add to your main class @ComponentScan(basePackages={"the package of your config swagger class"})

访问 url 必须是 http://localhost:port/context-path 如果你有它/swagger-ui.html

Th acces url must be http://localhost:port/context-path if you have it/swagger-ui.html

这篇关于Spring Boot Swagger HTML 文档未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆