-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Springfox integration issue for Swagger2 with Spring boot application #783
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
what do you get when you hit `http://localhost:8081/springfox/swagger-ui.html'? |
I see the same error as i explained above: 2015-06-09 13:22:02.974 WARN 9715 --- [nio-8081-exec-1] o.s.web.servlet.PageNotFound : No mapping found for HTTP request with URI [/springfox/swagger-ui.html] in DispatcherServlet with name 'dispatcherServlet' Also i see that common error page in the browser as well. Do i need to add any static content to resources folder ? Or i am missing any configuration w.r.t springfox and swagger ? |
My bad could you check |
i tried the above URL as well and the same error i see for that page: |
Am i missing any configurations related to springfox/Swagger2 ? Also do i need to copy any static content to resource folder ? FYI, i have already copied the dist folder contents under ///src/main/resources/static/swagger Any help is greatly appriciated |
Do i need to configure this ?
package springfoxdemo.java.swagger;
|
Only if you are not using spring-boot |
So in that case, i am using spring boot so i dont need this configuration. Any other clue ? |
What about
|
@dilipkrish - Could you please help me setting up springfox with spring boot ? |
Have you looked at https://github.com/springfox/springfox-demos? It has a complete |
Its not maven supported otherwise i could have build it on my local and test it....But still let me take a look at the configuration files atleast |
There is nothing maven or gradle specific in the build, other than how you launch the application like tomcat/boot plugins. |
@dilipkrish - I am new to both springfox as well as spring-boot, so its taking sometime for me to understand the integration. But now i have looked at the demo application and i have setup my application exactly same way but i am still seeing the same error which i have posted above. Here is my Spring boot MicroService: package com.diginsite.microservices;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
@SpringBootApplication
public class BusinessBankingService extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(BusinessBankingService.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(BusinessBankingService.class, args);
}
} Here is my WebMvcConfiguration.java: package com.diginsite.microservices;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.http.converter.xml.Jaxb2CollectionHttpMessageConverter;
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.oxm.xstream.XStreamMarshaller;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import org.springframework.web.servlet.view.xml.MarshallingView;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Configuration
@Import(Swagger2SpringBoot.class)
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
private static final String contextPath="com.intuit.schema.domain.banking.account.v2:"+
"com.intuit.schema.domain.banking.accounttransaction.v2:" +
"com.intuit.schema.domain.banking.image.v2:" +
"com.intuit.schema.domain.banking.ficustomer.v2:" +
"com.intuit.schema.domain.banking.financialinfo.v2:" +
"com.intuit.schema.domain.banking.financialinstitution.v2:" +
"com.intuit.schema.domain.banking.fundingaccount.v2:" +
"com.intuit.schema.domain.banking.location.v2:" +
"com.intuit.schema.domain.banking.scheduledtransfer.v2:" +
"com.intuit.schema.domain.banking.transfer.v2:" +
"com.intuit.schema.domain.billpay.billpayment.v2:" +
"com.intuit.schema.domain.billpay.payee.v2:" +
"com.intuit.schema.fs.common.v2:" +
"com.intuit.schema.domain.banking.configuration.v2:" +
"com.intuit.schema.domain.banking.auditdata.v1:"+
"com.intuit.schema.fs.alternatecredentials.v2:" +
"com.intuit.schema.domain.banking.businessbanking.v1"
;
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON);
configurer.defaultContentTypeStrategy(webRequest -> {
if(webRequest.getHeader("Content-Type") != null) {
switch(webRequest.getHeader("Content-Type")) {
case MediaType.APPLICATION_JSON_VALUE:
return Arrays.asList(MediaType.APPLICATION_JSON);
case MediaType.APPLICATION_XML_VALUE:
return Arrays.asList(MediaType.APPLICATION_XML);
default:
return Arrays.asList(MediaType.APPLICATION_JSON);
}
} else {
return Arrays.asList(MediaType.APPLICATION_JSON);
}
});
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
MarshallingHttpMessageConverter xmlConverter = marshallingHttpMessageConverter();
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
xmlConverter.setMarshaller(jaxb2Marshaller);
xmlConverter.setUnmarshaller(jaxb2Marshaller);
converters.add(xmlConverter);
converters.add(jaxb2CollectionHttpMessageConverter());
converters.add(jaxb2RootElementHttpMessageConverter());
stringConverter.setWriteAcceptCharset(false);
converters.add(new ByteArrayHttpMessageConverter());
converters.add(stringConverter);
converters.add(new ResourceHttpMessageConverter());
converters.add(new SourceHttpMessageConverter<>());
converters.add(new AllEncompassingFormHttpMessageConverter());
converters.add(jackson2Converter());
}
@Bean
public MarshallingHttpMessageConverter marshallingHttpMessageConverter() {
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setContextPath(contextPath);
jaxb2Marshaller.setPackagesToScan("com.intuit.schema.domain.banking.businessbanking.v1");
jaxb2Marshaller.setCheckForXmlRootElement(false);
jaxb2Marshaller.setSupportJaxbElementClass(true);
MarshallingHttpMessageConverter converter = new MarshallingHttpMessageConverter();
converter.setMarshaller(jaxb2Marshaller);
converter.setUnmarshaller(jaxb2Marshaller);
converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_XML));
return converter;
}
@Bean
public ContentNegotiatingViewResolver contentNegotiatingViewResolver() {
ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();
MarshallingView xmlView = new MarshallingView();
XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
xstreamMarshaller.setAutodetectAnnotations(true);
xmlView.setMarshaller(xstreamMarshaller);
xmlView.setContentType("application/xml");
MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
jsonView.setContentType("application/json");
jsonView.setDisableCaching(false);
contentNegotiatingViewResolver.setDefaultViews(Arrays.asList(xmlView, jsonView));
ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager(webRequest -> {
if(webRequest.getHeader("Content-Type") != null) {
switch(webRequest.getHeader("Content-Type")) {
case MediaType.APPLICATION_JSON_VALUE:
return Arrays.asList(MediaType.APPLICATION_JSON);
case MediaType.APPLICATION_XML_VALUE:
return Arrays.asList(MediaType.APPLICATION_XML);
default:
return Arrays.asList(MediaType.APPLICATION_JSON);
}
} else {
return Arrays.asList(MediaType.APPLICATION_JSON);
}
});
contentNegotiatingViewResolver.setContentNegotiationManager(contentNegotiationManager);
Map<String, String> mediaTypes = new HashMap<>();
mediaTypes.put("xml", "application/xml");
mediaTypes.put("json", "application/json");
contentNegotiatingViewResolver.setMediaTypes(mediaTypes);
return contentNegotiatingViewResolver;
}
@Bean
public Jaxb2CollectionHttpMessageConverter jaxb2CollectionHttpMessageConverter() {
Jaxb2CollectionHttpMessageConverter converter = new Jaxb2CollectionHttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_XML));
return converter;
}
@Bean
public Jaxb2RootElementHttpMessageConverter jaxb2RootElementHttpMessageConverter() {
Jaxb2RootElementHttpMessageConverter converter = new Jaxb2RootElementHttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_XML));
return converter;
}
@Bean
public MappingJackson2HttpMessageConverter jackson2Converter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper());
return converter;
}
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
return objectMapper;
}
// @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/");
// }
} Here is my Swagger Configuration java file: package com.diginsite.microservices;
import static com.google.common.base.Predicates.or;
import static com.google.common.collect.Lists.newArrayList;
import static springfox.documentation.builders.PathSelectors.regex;
import static springfox.documentation.schema.AlternateTypeRules.newRule;
import java.util.List;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.schema.WildcardType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import com.fasterxml.classmate.TypeResolver;
import com.google.common.base.Predicate;
@SpringBootApplication
@EnableSwagger2
@Configuration
@EnableWebMvc
@ComponentScan("com.diginsite.microservices.web")
public class Swagger2SpringBoot {
static final String detailDescription = "The `Business Banking Microservice` is a RESTful API that provides PD teams with out of the box functionality for Digital Insight's `Business Banking` suite of products. \n \n"
+"Below is a list of available REST API calls for business banking resources.";
@Autowired
private TypeResolver typeResolver;
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Swagger2SpringBoot.class, args);
}
@Bean
public Docket swaggerSpringMvcPlugin() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("v1-bbs")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.pathMapping("/v1")
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(newRule(typeResolver.resolve(DeferredResult.class,
typeResolver.resolve(ResponseEntity.class,
WildcardType.class)), typeResolver
.resolve(WildcardType.class)))
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.GET,
newArrayList(new ResponseMessageBuilder().code(500)
.message("500 message")
.responseModel(new ModelRef("Error")).build()))
.securitySchemes(newArrayList(apiKey()))
.securityContexts(newArrayList(securityContext()));
}
private Predicate<String> entitlementsAPIPaths() {
return or(
regex("/v1/fis/{fiId}/businessCustomers.*"),
regex("/v1/fis/{fiId}/companies/{companyId}/entitlements.*")
);
}
private ApiKey apiKey() {
return new ApiKey("mykey", "api_key", "header");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Overview")
.description(detailDescription)
.termsOfServiceUrl("http://springfox.io")
.contact("springfox")
.license("Apache License Version 2.0")
.licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE")
.version("2.0")
.build();
}
private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/anyPath.*")).build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope(
"global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList(new SecurityReference("mykey", authorizationScopes));
}
} Please let me know if i am doing anything wrong here....I used to start my microservice as a boot application in my Eclipse and test all my micro services... And now i am accessing http://localhost:8081/swagger-ui.html to see the swagger api documentation. I am sure there is a mistake the way i am integrating but not able to catch it...I hope you would have done lots of such integration and little clue will help me proceeding with this... Thanks in advance !! |
Remove the lines, in your configuration @Configuration
@EnableWebMvc I think that should fix it for you. |
@dilipkrish - Now i dont see the error which i was seeing before on the server log "No mapping found for HTTP request with URI [/swagger-ui.html]" . But i am not seeing the API documentation page in my browser . Its the same error page: Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Wed Jun 10 10:41:06 PDT 2015 |
Your I would suggest read up on how springboot works as compared to spring-mvc. |
:) Thanks for the update ! |
@dilipkrish - I am able to fix the issue and bring the swagger-ui.html working in my local. But i have couple of things which i wanted to configure:
Thnaks, |
@dpatra1 you can use the selector api and implement your own predicates if required. The getting started section has more info. Closing this issue as the origin issue has been addressed/answered |
@dilipkrish This is a old post and i have figured that out long back. |
Hi, I am using springfox to integrate swagger UI with spring boot application. I have exposed few rest APIs and have secured them using spring security. |
@Nantha2016 Cookies are not supported in swagger-ui I believe. |
Hi Dilip, Thanks for the link. |
You'd have to either implement it in your private copy of swagger-ui or push them to implement it. 😢 |
I'm having the same old issue:) and I think I have tried everything. <dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
<scope>compile</scope>
</dependency> My SwaggerConfig class: @Configuration
@EnableSwagger2
public class SwaggerConfig {
@Autowired
private Environment env;
@Bean
public Docket api() {
Docket docket = new Docket(DocumentationType.SWAGGER_2).groupName("myApi").
select()
.apis(RequestHandlerSelectors.basePackage("net.ws.controller"))
.paths(PathSelectors.any()).build();
return docket;
}
} Any idea what I'm doing wrong? |
What version of swagger UI are you using? This is a very old issue, please open a new issue if you feel its a new issue, it will help us prioritize it better. |
Sorry for writing here. I don't know if it's old or new. I tried with older versions as well, and same result. But I'm using 2.5.0 now. |
Since its a javascript error it would be useful to know what the URL was that failed with a 405 error. |
I tried with server.contextPath=/ and server.contextPath=/random |
|
@dilipkrish @objectivePinta fix the bugs in the use of mvc ,then swagger-ui appeared in all its glory. the error stack when open http://localhost/swagger-ui.html in the browser 👍 |
Sorry for answering so late. My problem was that the login endpoint had as request mapping "/". Make sure none of your rest end points answer to the default path. After changing it to "/login", swagger-ui appeared in all its glory. |
Hi, Recently we started moving it to Spring Boot and started migrating to JavaConfig, and I am stuck with an issue now. If I enable @configuration tag in WebConfig file, it will Not display The swagger page End points. {code} import com.inq.test.config.WebConfig; TestAPIApplication.class @bean @bean } SwaggerConfig class import com.google.common.base.Predicates; import javax.servlet.ServletContext; import static com.google.common.collect.Lists.newArrayList; @import({ AppConfig.class })
} WebConfig class {code} import com.inq.test.config.AppConfig; @configuration @OverRide
/*@OverRide /* @OverRide /* @OverRide @configuration {code} |
Hello @dilipkrish I read the above comments made by you and it solved my problem. Thanks a lot. |
I had this problem, and I have this setting: spring.resources.add-mappings=false in my application.properties file. Commenting out this line will make springfox swagger work, but my ResponseEntityExceptionHandler won't work for me. I need it to generate a custom error message back for any exception the user might encounter |
I was able to run swagger-ui and having custom error messages in my endpoints by modifying WebMvcConfigurerAdapter. But I'm not really sure if this has side effects. This is my code:
|
Using @EnableWebMvc does have consequences. It will not auto configure your mvc components |
I found the really reason, because of @componentscan, and u must to annotate it , for example: and then , it will be ok, u can open the swagger-tui.html and /swagger-resources/configuration/ui |
swagger启动后,老是报错下面的url无法打开swagger-ui.html, 原因是: 解决办法:注释掉扫描注解即可: |
Hii, my application is inheriting from WebMvcConfiguration ,and i am getting 404 eror for swgger,how can i fix that |
I integrated swagger 2 and Spring Boot, and I found a error as following. How to fix this issue? Whitelabel Error PageThis application has no explicit mapping for /error, so you are seeing this as a fallback. Mon Jul 15 22:02:19 PDT 2019 There was an unexpected error (type=Not Found, status=404). No message available
|
@wx8900 hi, please help me. |
Hi
I am new to Springfix and Swagger2 as well. So i am in a project where all the latest technologies are used like: java8, Spring boot etc and we wanted to integrate Swagger2 with Springfox to generate the APi documentation.
I have gone through the 'http://springfox.github.io/springfox/docs/snapshot/' page but i am still having issue and i dont see the Swagger Ui api documentation page .
Its giving me an error in the tomcat server when i am trying to hit:
'http://localhost:8081/springfox/'
WARN 6872 --- [nio-8081-exec-1] o.s.web.servlet.PageNotFound : No mapping found for HTTP request with URI [/springfox/] in DispatcherServlet with name 'dispatcherServlet'
I have a feeling that i am still missing some configuration w.r.t the static resources which is causing this issue.
Can you please help me here ?
Here are my dependencies and configurations.
io.springfox
springfox-swagger2
2.0.1
org.webjars
swagger-ui
2.1.8-M1
Swagger2 java configuration:
package com.diginsite.microservices;
import static com.google.common.collect.Lists.newArrayList;
import static springfox.documentation.schema.AlternateTypeRules.newRule;
import java.util.List;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.schema.WildcardType;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import com.fasterxml.classmate.TypeResolver;
@EnableSwagger2
@Configuration
@EnableWebMvc
@ComponentScan("com.diginsite.microservices.web")
public class Swagger2SpringBoot {
@Autowired
private TypeResolver typeResolver;
}
How i am testing: I am running my MicroService using spring boot and trying to hit the above URL.
Thanks,
Deba
The text was updated successfully, but these errors were encountered: