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,但没有列出任何控制器。下拉列表为空,如下所示
**我目前面临的问题是
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)
在将一个较旧的项目从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应用程序上下文中)
有关相关问题的其他一些注意事项:
/webjars/springfox-swagger-ui/springfox.js/webjars/springfox-swagger-ui/swagger-ui-bundle.js/webjars/springfox-swagger-ui/swagger-ui-standalone-preset.js/webjars/**/swagger-ui.html/v2/api-docs/swagger-resources/**您需要在 Swagger UI 中指向生成的 Swagger Definition。即代替http://example.com/api给你的招摇定义路径类似 http://localhost:8080/RestResource/api/swagger.json
| 归档时间: |
|
| 查看次数: |
6670 次 |
| 最近记录: |