springspring-bootswagger

Is it possible to implement Swagger in a common library with Spring-boot?


I have several projects that are independent, so they are not related to each other, however, they are built with a very similar structure and I tried to implement Swagger in one of these and it worked well. But now, I would like to know if it is possible to create a common library for Swagger and its additional configuration because the project works with Spring-boot and Groovy, so there is an additional code in addition to the normal Swagger configuration, and what I'm trying to do is to avoid all this boilerplate code and just have a library with this config.

Is this possible? How can I achieve that? Is there any other better approach to do this?


Solution

  • This is possible, you just need to create a bean in a common library with the boilerplate code, add the library as a dependency in your project, and then import that bean into a configuration class in your project.

    Swagger boilerplate in commons library:

    @Configuration
    @EnableSwagger2
    @Import(BeanValidatorPluginsConfiguration.class)
    public class SwaggerConfiguration implements WebMvcConfigurer {
    
        @Bean 
        public Docket getSwagger() {
            return new Docket(DocumentationType.SWAGGER_2)
                .[method chaining boilerplate here]
        }
    }
    

    Config class in project (usually class annotated with @SpringBootApplication):

    @SpringBootApplication
    @Import(SwaggerConfiguration.class)
    public class Main() {}