4
votes

I have a Spring Rest controller and its NOT spring boot application. Its just a REST API Project. I want to integrate swagger2 in my project. I tried all the examples in Net and in demo but with no luck. When i try to execute http://localhost:8085/context/swagger-ui.html i get 404 error. Please find my confugration below and let me know if there is any discrepencies. Any help is highly appreciated.

jars - under /WEB-INF/lib

google-collections-1.0.jar springfox-core-2.2.2.jar springfox-schema-2.2.2.jar springfox-spi-2.2.2.jar springfox-spring-web-2.2.2.jar springfox-staticdocs-2.2.2.jar springfox-swagger-common-2.2.2.jar springfox-swagger-ui-2.2.2.jar springfox-swagger2-2.2.2.jar

My swagger config class -

@EnableSwagger2
public class SwaggerConfiguration {

}

My springconfig class

@EnableWebMvc
@ComponentScan(basePackageClasses = controller.class)
@Import(SwaggerConfiguration.class)
public class SpringConfiguration extends WebMvcConfigurerAdapter {

@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/");
}
}

My Application initializer class below as per springfox-java demo . I tried with and without the below class and its not working either way.

Application Initializer class

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return new Class[]{controller.class};
}

@Override
protected String[] getServletMappings() {
    return new String[]{"/*"};
}
}

I can access my rest urls but not swagger-ui.html in the same context.

Please let me know what i am missing here?

2
Can you see something similar in your startup logs: Mapped "{[/swagger-resources/configuration/ui]}" onto org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.UiConfiguration>P_W999

2 Answers

1
votes

I add the manual selection of controllers:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("my.package.to.api"))
                .paths(regex("/product.*")) //optional 
                .build();

    }
}
0
votes

given details are not sufficient to reproduce/analyse the issue.

But, today I faced similar problem, ofcourse used SpringBoot, and solved myself as below: as my sample have one controller class and an application class having main method, I created packages as below, and it got solved:

  • hello
    • controllers
      • HelloController
    • swagger
      • SwaggerConfig2
    • HelloApplication