Swagger UI没有列出任何控制器/端点,尽管我能够在v2 / api-docs端点下看到json

ser*_*rah 6 rest swagger swagger-ui spring-4 swagger-2.0

我无法使Swagger UI与我的项目一起使用。Swagger UI很好用,但是它没有列出我的任何REST控制器。

我正在使用SPRING 4.2.6.RELEASE和Swagger 2.5.0。我的其余服务已部署到Tomcat 7.0.54。

当Tomcat 7.0.54出现时,它能够获取迅速的端点。我能够找到提取json消息的端点v2 / api-docs。我也可以点击swagger-ui,但没有列出任何控制器。下拉列表为空,如下所示

在此处输入图片说明

**我目前面临的问题是

  1. 我无法获取/ swagger-resources / configuration / ui,而当我启动swagger UI时却遇到404(未找到)错误,而该UI试图获取/ swagger-resources / configuration / ui。我为swagger-resources安装了资源处理程序,但这似乎无济于事。您能否让我知道可能会丢失什么?
  2. 我应该在扩展的WAR中看到META-INF下的resources文件夹吗?META-INF内应该有任何与springfox相关的文件/文件夹吗?**

Swagger的Maven依赖项
io.springfox springfox-swagger2 2.5.0
io.springfox springfox-swagger-ui 2.5.0

以下是我的SwaggerCongifuration

@EnableSwagger2
public class SwaggerConfiguration {

@Bean
public Docket api() {
    List<SecurityContext> security = new ArrayList<SecurityContext>();
    security.add(securityContext());
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .pathMapping("/").securityContexts(security);
}

private SecurityContext securityContext() {
    return SecurityContext.builder()
            .forPaths(PathSelectors.regex("/"))
            .build();
 }
}
Run Code Online (Sandbox Code Playgroud)

下面是我的WebConfig.xml

@EnableWebMvc
@Configuration
@Import(SwaggerConfiguration.class)
@ComponentScan("com.bank.direct.services")

public class WebConfig extends WebMvcConfigurerAdapter {


@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> pConverters) {
    pConverters.add(RestUtils.getJSONMessageConverter());
}


@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
    .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
    .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

}
Run Code Online (Sandbox Code Playgroud)

以下是SecurityCongif.xml

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


@Autowired
private AuthenticationService _authenticationService;


@Autowired
public void globalUserDetails(AuthenticationManagerBuilder pAuth) throws Exception {

    pAuth.userDetailsService(_authenticationService);
}


@Override
protected void configure(HttpSecurity pHttp) throws Exception {

    // Enable HTTP caching
    pHttp.headers().cacheControl().disable();

    // Configure security
    pHttp.httpBasic()

    // -- Allow only authenticated request
    .and()
    .authorizeRequests()
    .anyRequest().authenticated()

    // -- Logout configuration
    .and()
    .logout()
    .logoutUrl("/rest/users/logout/")
    .deleteCookies("XSRF-TOKEN")
    .logoutSuccessUrl("/static/index.html")
    .invalidateHttpSession(true)

    // -- CSRF configuration
    .and()
    .csrf().csrfTokenRepository(csrfTokenRepository())
    .and()
    .addFilterAfter(csrfHeaderFilter(), SessionManagementFilter.class);

}


private Filter csrfHeaderFilter() {

    return new OncePerRequestFilter() {

        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
            if (csrf != null) {
                Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                String token = csrf.getToken();
                if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                    cookie = new Cookie("XSRF-TOKEN", token);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
            filterChain.doFilter(request, response);
        }
    };
}


private CsrfTokenRepository csrfTokenRepository() {
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    repository.setHeaderName("X-XSRF-TOKEN");
    return repository;
}
Run Code Online (Sandbox Code Playgroud)

Rest Controller类如下

@RestController
@RequestMapping(value = "/vehicles", produces =     MediaType.APPLICATION_JSON_UTF8_VALUE)
public class VehicleResource extends Resource {

@Autowired
private IVehicleService _vehicleService;

@RequestMapping(value = "/brands", method = RequestMethod.GET)
public APIResponseEntity getBrands(WebRequest pWebRequest) {

    IUser user = getUser(pWebRequest);
    BrandCriteria criteria = new BrandCriteria();
    criteria.setLanguageCode(user.getLanguageCode());

    List<Brand> res = _vehicleService.getBrands(user, criteria);

    return newResponseOK(res);
}

@RequestMapping(value = "/brands/{brand_code}", method = RequestMethod.GET)
public APIResponseEntity getBrand(WebRequest pWebRequest, @PathVariable("brand_code") String pBrandCode) {

    IUser user = getUser(pWebRequest);
    BrandCriteria criteria = new BrandCriteria();
    criteria.setLanguageCode(user.getLanguageCode());
    criteria.setBrandCode(pBrandCode);
    List<Brand> res = _vehicleService.getBrands(user, criteria);
    return newResponseOK(res);
 }
}   
Run Code Online (Sandbox Code Playgroud)

trf*_*trf 5

在将一个较旧的项目从XML Spring配置迁移到Java Spring配置并更新spring和Swagger版本之后,我遇到了一个听起来像这样的问题,因此我想在这里记录我的解决方案。

我遇到了很多问题,但与OP场景相符的主要问题是,虽然/v2/api-docs可以访问并返回JSON,但显然没有拾取我的Controller,并且当我访问Swagger UI时/swagger-ui.html,我得到404的信息页面试图请求/swagger-resources/configuration/ui

我的Swagger配置类是:

@Configuration
@EnableSwagger2
public class SwaggerWebConfig {
    @Bean
    public Docket api() {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

@ EnableSwagger2批注导入另一个配置类Swagger2DocumentationConfiguration,该类又导入SwaggerCommonConfiguration,后者对组件进行组件扫描以查找springfox.documentation.swagger.web最终装入ApiResourceController的类。

  • /swagger-resources/
  • /swagger-resources/configuration/security
  • /swagger-resources/configuration/ui

被送达。

我不正确的是,当SwaggerWebConfig类应该属于Web应用程序上下文时,它是由根应用程序上下文加载的请参阅ApplicationContext与WebApplicationContext)。

Web应用程序上下文中的Bean可以访问根应用程序上下文中的Bean,但不能反过来,这解释了为什么Docket Bean(在根应用程序上下文中错误地)无法在Web应用程序上下文中拾取@Controller Bean,以及解释了为什么尽管创建了ApiResourceController bean,但尝试访问它们时其方法却给出了404(它们应该在Web应用程序上下文中)

有关相关问题的其他一些注意事项:

  • 如果您可以访问v2 / api-docs,则说明Docket Bean正在运行
  • 在非spring-boot环境中,您需要自己注册两个资源处理程序,因为spring boot的自动配置将为您完成此操作,如对此问题的答案所述。那应该解决404的问题:
    • /swagger-ui.html(即404提取实际的html swagger-ui.html页面)
    • 以及swagger-ui.html加载的三个webjar:
      • /webjars/springfox-swagger-ui/springfox.js
      • /webjars/springfox-swagger-ui/swagger-ui-bundle.js
      • /webjars/springfox-swagger-ui/swagger-ui-standalone-preset.js
  • 如果您获得拒绝访问而不是未找到404的请求,那么如此答案所示,您可能需要告知spring安全性以允许访问:
    • /webjars/**
    • /swagger-ui.html
    • /v2/api-docs
    • /swagger-resources/**


Gee*_*eek 1

您需要在 Swagger UI 中指向生成的 Swagger Definition。即代替http://example.com/api给你的招摇定义路径类似 http://localhost:8080/RestResource/api/swagger.json

这篇文章可能对你有更多帮助