Spring Boot Swagger HTML文档未显示

时间:2018-12-21 02:24:20

标签: spring-boot swagger-ui

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

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

<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配置类:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

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

我在尝试访问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

请在以下控制器之一中查找:

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);
    }
}

1 个答案:

答案 0 :(得分:0)

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();
    }
}

以下是控制器的示例:

@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){
            }

    }

您可以使用该类进行测试,但是我想您已经在控制器中编写了所有醒目的注解!

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

访问网址必须为http://localhost:port/context-path if you have it/swagger-ui.html