Swagger UI is not rendering on the browser - java

I have added swagger dependencies to the spring boot application and JSON is loading as expected. When I try to load UI by calling this URL http://localhost:9090/swagger-ui.html then the following error is displayed on the browser.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
There was an unexpected error (type=Not Found, status=404).
pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
config class
#Configuration
#EnableSwagger2
public class SwaggerConfig {
}
Ps - My application is running under the port 9090

I found the solution. From Swagger 3.0 we don't need to add 2 dependencies into the build tool. springfox-boot-starter can be replaced instead of those 2 dependencies.
pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
Form swagger 3.0 the URL should be http://localhost:9090/swagger-ui/rather than http://localhost:9090/swagger-ui.html

i had similar issue. Make sure you declerate the swagger items.
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//Swagger UI property
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
This must be declareted in the config of implementation with "WebMvcConfigurer".
More information here : https://springfox.github.io/springfox/docs/current/

If you have base url defined, for eg /rest, /api then you will need to put that as well.
My config looks like this:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
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;
#Configuration
#EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter{
#Bean
public Docket APIs() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(metadata())
.select()
.apis(RequestHandlerSelectors.basePackage("<rest_controller_package>"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo metadata() {
return new ApiInfoBuilder()
.title("<title_here>")
.description("<description_here>")
.version("BETA")
.build();
}
}
and pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
and I access it via http://localhost:9090/api/swagger-ui.html

I think you should add into the SwaggerConfig class a Bean that return a Docket object, which specify the paths and the packages that you want to show in swagger. Something like this:
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage(“com.spring.rest.controller”))
.paths(PathSelectors.any())
.build();
}
}

Related

Jax-rs annotation Path is not work in java spring boot?

I have spring boot application with starter version 2.1.16, and spring-boot-starter-web dependency. So, i want use javax.ws.rs-api library, and add dependency:
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1.1</version>
</dependency>
So when i create controller, and add #Path, #Get - i don't get answer from the server (404 not found). How makes it work?
package com.example.test;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.ext.Provider;
#RestController
public class MyController {
//Doesn't work (404 not found
#GET
#Path("/my_test")
public String check() {
return "hi!";
}
//Work
#RequestMapping("/my_test2")
public String check2() {
return "hi2!";
}
}
Add the following dependency in your pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
</dependencies>
if you use spring boot starter version 2.1.16, you will normally have a parent pom which will also define the default version for the above dependency.
Then replace #RestController with #Path("/") from package javax.ws.rs.Path
Now it should be working.
Keep in mind your embedded server now, will be jersey instead of default tomcat.
Edit: Also as found from the author of the question another change is needed to register a ResourceConfig. This is also described here in the official documentation.
In addition to the post above, you need to add the config class:
#Configuration
public class JerseyConfig {
#Bean
public ResourceConfig resourceConfig(MyController myController) {
ResourceConfig config = new ResourceConfig();
config.register(myController);
return config;
}
}

Getting error while configuring Swagger-ui with spring reactive

While integrating swagger-ui with a reactive spring project generated using JHipster 7.1.0 for Java 11. I added the below dependencies.
The application has below dependencies of swagger
POM dependencies
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-common</artifactId>
<version>1.4.3</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-webflux-core</artifactId>
<version>1.4.3</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-webflux-ui</artifactId>
<version>1.4.3</version>
</dependency>
Apart from that we added a configuration SwaggerConfig.java
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import org.springdoc.core.GroupedOpenApi;
import org.springdoc.core.customizers.OpenApiCustomiser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
#OpenAPIDefinition(info = #Info(title = "Amazingbabbage", version = "1.0", description = "Documentation APIs v1.0"))
public class SwaggerConfig {
#Bean
public GroupedOpenApi employeeGroupApi() {
return GroupedOpenApi.builder()
.group("all")
.pathsToMatch("/api/**")
.build();
}
public OpenApiCustomiser getOpenApiCustomiser() {
return openAPI -> openAPI.getPaths().values().stream().flatMap(pathItem ->
pathItem.readOperations().stream())
.forEach(operation -> {
operation.addParametersItem(new Parameter().name("Authorization").in("header").
schema(new StringSchema().example("token")).required(true));
operation.addParametersItem(new Parameter().name("userId").in("header").
schema(new StringSchema().example("test")).required(true));
});
}
}
{
"type" : "https://www.jhipster.tech/problem/problem-with-message",
"title" : "Internal Server Error",
"status" : 500,
"detail" : "No primary or single public constructor found for interface org.springframework.http.server.reactive.ServerHttpRequest - and no default constructor found either",
"path" : "/swagger-doc/swagger-ui.html",
"message" : "error.http.500"
}
Please share your feedback or inputs if you have faced similar issues.
When you have both Spring MVC and Webflux are present, Spring Boot will configure your application to use Spring MVC only. (see : https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.spring-application.web-environment)
You need to ensure that the Spring MVC dependency is not present in your project.

In Spring Data Rest, Swagger2 configuration issue by using profile

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-data-rest</artifactId>
<version>3.0.0-SNAPSHOT</version>
</dependency>
#Profile({"dev-test", "local-test"})
#Configuration
#EnableSwagger2WebMvc
public class SwaggerConfig {
#Bean
public Docket documentation() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(s -> s.matches("/_api/.*"))
.build();
}
}
This error occurs when the profile is not local-test or dev-test.
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 4 of constructor in springfox.documentation.spring.data.rest.EntityServicesProvider required a bean of type 'com.fasterxml.classmate.TypeResolver' that could not be found.
Action:
Consider defining a bean of type 'com.fasterxml.classmate.TypeResolver' in your configuration.
Hi, i'm using Swagger3.0 with Spring Data Rest.
This is the link I referenced.
https://stackoverflow.com/a/46458135/10345277
What I'm doing is trying to turn the Swagger on or off by Profile.
However, unlike the above link, I use SDR and springfox.documentation.spring.data.rest throws an error.
Is there a solution?
In my case - using io.springfox:springfox-swagger2:2.9.2 and io.springfox:springfox-swagger-ui:2.9.2 - this error war triggered because I forgot to add #EnableSwagger2 to my #Configuration class
my swagger3.0 is fine,like this:
#ConditionalOnClass(value = {Swagger.class})
#Profile({"dev", "test"})
#Configuration
#EnableSwagger2
public class SwaggerConfig {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("your base package"))
.paths(PathSelectors.any())
.build();
}

Springboot swagger url shows WhiteLabel Error page

Here is my code: I am getting all the values from application.properties file
SwaggerConfig.java
#Configuration
#EnableSwagger2
#Profile("!prod")
#PropertySource(value = { "classpath:application.properties" })
public class SwaggerConfig {
#Value("${swagger.api.title}")
private String title;
#Value("${swagger.api.description}")
private String description;
#Value("${swagger.api.termsOfServiceUrl}")
private String termsOfServiceUrl;
#Value("${swagger.api.version}")
private String version;
#Value("${swagger.api.controller.basepackage}")
private String basePackage;
#Bean
public Docket postMatchApi() {
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage(basePackage))
.paths(PathSelectors.ant("/**")).build().apiInfo(metaData());
}
private ApiInfo metaData() {
return new ApiInfoBuilder().title(title).description(description).termsOfServiceUrl(termsOfServiceUrl)
.version(version).build();
}
Here is my springboot initializer:
#SpringBootApplication
#ComponentScan(basePackages = { "com.example.demo" })
#ComponentScan(basePackageClasses = {AppInitializer.class, SwaggerConfig.class})
#EnableAsync
#EnableRetry
public class AppInitializer{
public static void main(String[] args) {
SpringApplication.run(AppInitializer.class, args);
}
}
ServletInitializer.java
public class ServletInitializer extends SpringBootServletInitializer implements WebApplicationInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(PostMatchAppInitializer.class);
}
}
The log says it is mapped:
[INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[],methods=[POST],consumes=[application/json],produces=[application/json]}" onto public <T> org.springframework.http.ResponseEntity<?> com.,org.springframework.validation.BindingResult) throws java.lang.Exception
[INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/v2/api-docs],methods=[GET],produces=[application/json || application/hal+json]}" onto public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)
[INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/swagger-resources/configuration/ui]}" onto org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.UiConfiguration> springfox.documentation.swagger.web.ApiResourceController.uiConfiguration()
[INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/swagger-resources]}" onto org.springframework.http.ResponseEntity<java.util.List<springfox.documentation.swagger.web.SwaggerResource>> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
[INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/swagger-resources/configuration/security]}" onto org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.SecurityConfiguration> springfox.documentation.swagger.web.ApiResourceController.securityConfiguration()
[INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
[INFO ] 2018-01-17 16:46:37.071 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
[INFO ] 2018-01-17 16:46:37.227 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#5e89f6: startup date [Wed Jan 17 16:46:34 CST 2018]; root of context hierarchy
This is the error that i get:
[WARN ] 2018-01-17 16:46:42.217 [http-nio-8082-exec-1] o.s.w.s.PageNotFound - No mapping found for HTTP request with URI [/example/swagger-ui.html] in DispatcherServlet with name 'dispatcherServlet'
For the new Springfox version(3.0.0) you need to do something different
In pom.xml add the following dependency
*
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
instead of two for
<artifactId>springfox-swagger2</artifactId> and
<artifactId>springfox-swagger-ui</artifactId>
and access ../swagger-ui/ instead of ../swagger-ui.html
For Swagger 3.0, the URL is changed
http://localhost:8080/swagger-ui/index.html
I found what the issue was, in one of the config files i somehow had #EnableMvc annotation due to which the dispatcherservlet was looking for the mapping /example/swagger-ui.html and since it could not find one it was complaining "No Mapping found".
After removing #EnableMvc it is working perfectly fine.
For others like me that is still getting the "Whitelabel" page error, check if you have:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
in your pom.xml file, it's not only the "springfox-swagger2" dependency required as the official doc page shows, you need "springfox-swagger-ui" too.
I faced the same issue. So Basically if you are using spring 3 or more then to open the swagger page , you have to do 3 things only.
Add 3 dependencies in pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2 </artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
Create a config file.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2);
}
}
Open this link to access the API.
http://localhost:8080/swagger-ui/
Now just match which step you missed. Do ask if you get stuck somewhere.
I'm bad at English, that's why GoogleTranslate.
That version and way of doing it is already a bit outdated, if you want the documentation to be generated automatically, SpringDoc simplifies the generation and maintenance of API documents, based on the OpenAPI 3 specification, for Spring Boot 1.x and 2.x. applications.
For magic to happen we simply add the dependency to our pom:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.2.32</version>
</dependency>
then access the description that already has it http://localhost:8080/v3/api-docs/
and for swagger: http://localhost:8080/swagger-ui.html
that's all there is to it.
for more detail
if you want to customize the api information you can include java style annotations:
#OpenAPIDefinition(
info = #Info(
title = "API personas",
description = "Este es un ejemplo de servidor Personas-Server."
+ "Usted puyede encontrar mas acerca de Swagger " ++"[http://swagger.io](http://swagger.io) o en "
+ "[irc.freenode.net, #swagger](http://swagger.io/irc/).",
termsOfService = "http://swagger.io/terms/",
license = #License(
name = "Apache 2.0",
url = "http://springdoc.org"),
version = "otra"
))
#Tag(name = "persona", description = "API para personas")
#RestController
#RequestMapping("persona")
public class PersonaRest extends GeneralRest {}
can also be generated for special methods:
#Operation(
summary = "traer todas las personas",
description = "api para traer todas las personas, aqui no se tienen en cuenta paginaciones, ni filtros, trae todos los registros",
tags = { "persona" }
)
#ApiResponses(
value = {
#ApiResponse(
responseCode = "200",
description = "Operación exitosa",
content = #Content(
mediaType = "application/json",
array = #ArraySchema(
schema = #Schema(
implementation = PersonaTO.class
)))),
#ApiResponse(
responseCode = "401",
description = "Sin autorización",
content = #Content(
mediaType = "application/json",
schema = #Schema(
implementation = Object.class
))),
})
#GetMapping
public List personas() {
return personaServicio.obtenerTodo();
}
it is always good practice to use the most recent libraries and inclusions.
For me it is swagger dependency version.
Issue with
spring boot - 2.3.4
java - 8
swagger - 3.0.0
No issue with
spring boot - 2.3.4
java - 8
swagger - 2.9.2
Move swagger configuration to your SpringBootApplication class. That will solve the whitable page error.
If your facing the issue even after adding appropriate dependencies
Then follow the below steps
1.Go to C:\Users\User.m2
2.Delete the repository folder (Complete folder delete i.e Shift+Delete button windows)
This folder bascially contains all the jars that your project requires
So when you again open your project it will automatically download the dependencies
first, add below dependencies in spring boot pom file, then add #EnableSwagger annotation on the application class and then add webappconfig class
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.1</version>
</dependency>
#Configuration
#EnableWebMvc
public class ApplicationWebMvcConfig implements WebMvcConfigurer {.
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}.
For SpringBoot Ver: 2.4.0-M4 I recommend the following setup.
Make sure you use SpringFox ver: 3.0.0
//build.gradle file
def springFoxVer = '3.0.0'
def log4jVer = '2.13.3'
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
implementation 'org.springframework.boot:spring-boot-starter-hateoas'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.data:spring-data-rest-hal-explorer'
implementation "io.springfox:springfox-swagger2:$springFoxVer"
implementation "io.springfox:springfox-boot-starter:$springFoxVer"
implementation "io.springfox:springfox-swagger-ui:$springFoxVer"
implementation "io.springfox:springfox-data-rest:$springFoxVer"
implementation "org.apache.logging.log4j:log4j-core:$log4jVer"
implementation "org.apache.logging.log4j:log4j-api:$log4jVer"
implementation 'org.springframework.boot:spring-boot-starter-actuator'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.h2database:h2'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
In the configuration class:
#Configuration
public class SwaggerDocumentationConfig {
ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Sample Indentity in Project")
.description("The identity API provides standardized mechanism for identity management such as creation, update, retrieval, deletion. Party can be an individual or an organization that has any kind of relation with the enterprise. ### Resources - Individual Party API performs the following operations : - Retrieve an individual - Retrieve a collection of individuals according to given criteria - Create a new individual - Update an existing individual - Delete an existing individual")
.license("")
.licenseUrl("http://unlicense.org")
.termsOfServiceUrl("")
.version("1.0.0")
.contact(new Contact("Sean Huni", "https://sean-huni.xyz", "sean2kay#gmail.com"))
.build();
}
#Bean
public Docket customImplementation() {
return new Docket(DocumentationType.SWAGGER_2)
.tags(new Tag("Person Entity", "Repository for People's entities"))
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
}
In the application-runner/executor class:
#SpringBootApplication
#EnableSwagger2
#EnableJpaRepositories
#Import(SpringDataRestConfiguration.class)
public class SpringSwaggerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSwaggerApplication.class, args);
}
}
As instructed here. Most cases just taking the time to read the requirements & the setup process means everything in terms of saving yourself a day of getting stuck.
In my case, I upgraded from swagger 2.7.0 to 3.0.0 and these were the steps to reach the honeypot:
add one dependency
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${swagger.version}</version>
</dependency>
remove two dependencies (but they do not harm, if you forget this step)
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
The Server-Class now looks like this (unchanged compared to swagger v2.7.0)
#SpringBootApplication(scanBasePackages = {"com.acme.product.server"})
#RestController
#EnableScheduling
#EnableSwagger2
public class AcmeProductServer {
// [...]
// --- swagger integration
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.acme.product.server"))
.build();
}
}
Then I really had to delete and refresh my local maven repository at 'C:\Users\Zaphod.m2\repository'
Last issue was to use a different URL: http://localhost:8080/iam/swagger-ui/ (without the trailing slash or '/index.html' at the end it does not work)
Ensure following things along with versions:
dependency is added
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
#Bean Dokcet is defined in #SpringBootApplication class
swagger ui endpoint http://localhost:<port-number>/swagger-ui
P.S: tested in spring boot (v2.5.0)
To include Swagger in our project, let's add the following annotation to our application void method.
#SpringBootApplication
#EnableSwagger2
public class PostApplication {
public static void main(String[] args) {
SpringApplication.run(PostApplication.class, args);
}
}
Simple install the Spring Fox boot starter and remove the springfox-swagger-ui and springfox-swagger2 from your project.
Gradle:-
implementation group: 'io.springfox', name: 'springfox-boot-starter', version: '3.0.0'
Maven:-
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
Also, create a file named SwaggerCondig.java with the below configurations
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.xxx.xxx.controller"))
.paths(PathSelectors.any()).build();
}
}
Access the swagger at http://localhost:9005/service-name/swagger-ui/
In my case I used mvn dependencies
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
calling http://localhost:8088/swagger-ui/ instead of http://localhost:8088/swagger-ui.html works for me. Also check basePackage is correct if you have swagger config file.
If anyone wants to work with Swagger UI then do these 3 simple steps
Step 1 -> Add Dependencies
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
Step 2 -> Goto main class and give annotation #EnableSwagger2
#SpringBootApplication
#EnableSwagger2
class PracticeApplication {
Step 3 -> Restart server & Just hit http://localhost:8080/swagger-ui/
Note - After doing this if anyone getting - "Failed to start bean 'documentationPluginsBootstrapper"
Then add the below line to application.properties -
spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER
if you use spring 3 like me, make sure to use these dependencies:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.0.2</version>
</dependency>
make sure to remove the annotation #EnableSwagger2 because it's not necessary in spring 3 as mentioned here https://github.com/springfox/springfox

Failing JUnit tests for embedded Fongo DB

I have a Spring Boot application which use MongoDB. I would like to use the embedded FongoDB for my JUnit tests. I follow some articles, for example:
http://dontpanic.42.nl/2015/02/in-memory-mongodb-for-unit-and.html
My Fongo test configuration looks like
package com.myproject.rest;
import com.github.fakemongo.Fongo;
import com.mongodb.Mongo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
#Profile("test")
#ComponentScan(basePackages = "com.myproject.service.data")
#EnableMongoRepositories(basePackages = "com.myproject.service.data.repository")
#Configuration
public class MongoTestConfig extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "demo-test";
}
#Bean
#Override
public Mongo mongo() {
return new Fongo("mongo-test").getMongo();
}
}
I have this dependency for that:
<dependency>
<groupId>com.github.fakemongo</groupId>
<artifactId>fongo</artifactId>
<version>2.1.0</version>
<scope>test</scope>
</dependency>
I would like to test my services which autowired a repository interface which extends MongoRepository
package com.myproject.service.data.repository;
import com.myproject.service.data.entity.JournalData;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
public interface JournalRepository extends MongoRepository<JournalData, String> {
#Override
public List<JournalData> findAll(Iterable<String> ids);
}
My tests class are inherited from the class below:
package com.myproject.rest;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import cz.csas.services.commons.api.RequestMetadata;
import org.junit.Before;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
#RunWith(PowerMockRunner.class)
#PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
#PowerMockIgnore({"javax.xml.*", "org.xml.*", "org.w3c.*", "javax.management.*", "javax.net.ssl.*"})
#PrepareForTest({RequestMetadata.class})
#ActiveProfiles("test")
public class EndpointTestContext {
#Autowired
protected MockMvc mockMvc;
//#Rule
//public MongoDbRule mongoDbRule = newMongoDbRule().defaultSpringMongoDb("demo-test");
#Before
public void setup() {
mockStatic(RequestMetadata.class);
when(RequestMetadata.builder()).thenCallRealMethod();
RequestMetadata m = RequestMetadata.builder()
.workingMode("TEST")
.build();
when(RequestMetadata.getMetadata()).thenReturn(m);
}
}
But when I run the Maven tests I recieve the following:
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.mongodb.MongoClientOptions
at com.mongodb.MockMongoClient.create(MockMongoClient.java:42)
at com.github.fakemongo.Fongo.createMongo(Fongo.java:175)
at com.github.fakemongo.Fongo.<init>(Fongo.java:88)
at com.github.fakemongo.Fongo.<init>(Fongo.java:75)
at com.github.fakemongo.Fongo.<init>(Fongo.java:67)
at com.myproject.rest.MongoTestConfig.mongo(MongoTestConfig.java:30)
at com.myproject.rest.MongoTestConfig$$EnhancerBySpringCGLIB$$bf18b1d4.CGLIB$mongo$1(<generated>)
at com.myproject.rest.MongoTestConfig$$EnhancerBySpringCGLIB$$bf18b1d4$$FastClassBySpringCGLIB$$3ab8bfd7.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
at com.myproject.rest.MongoTestConfig$$EnhancerBySpringCGLIB$$bf18b1d4.mongo(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 115 common frames omitted
Can anyone suggest how to fix it? Thank you in advance.
Fongo can't find class from mongo-java-driver artifact. It declares
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
as provided dependency. You should have mongo-java-driver on your test classpath. Most probably
<scope>runtime</scope>
or test will be enough for you.
Check if you have multiple version of mongo java driver (version conflicts). To check this, you can use mvn dependency tree to trace the path from where each jar is coming to your project.
mvn dependency:tree
Just need to find out the right version on mongo java driver and make sure you are not having version conflicts. I have used spring data and used fongo to write in-memory test case for mongodb queries.
<fongo-version>1.6.3</fongo-version>
<spring-data-mongodb-version>1.7.2.RELEASE</spring-data-mongodb-version>
<spring-framework-version>4.1.5.RELEASE</spring-framework-version>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${spring-data-mongodb-version}</version>
</dependency>
<dependency>
<groupId>com.github.fakemongo</groupId>
<artifactId>fongo</artifactId>
<version>${fongo-version}</version>
<scope>test</scope>
</dependency>
Version conflict can come from may source (can confirm using above mvc dependency:tree command, one such source is mongobee, so if you are using it, please exclude mongo-java-drive by using exclusion
<dependency>
<groupId>com.github.mongobee</groupId>
<artifactId>mongobee</artifactId>
<version>${mongobee-version}</version>
<exclusions>
<exclusion>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
</exclusion>
</exclusions>
</dependency>

Categories