lauhin
10/15/2019 - 6:40 PM

Swagger documentgeneratie met Spring

Swagger documentgeneratie met Spring

Via Springfox worden de restcontrollers gedocumenteerd naar een swagger bestand.

Maven dependencies

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>

Security

Deze klasse is nodig om te ontwijken aan authenticatie. Via deze klasse kan de swagger code via de browser ingelezen worden zonder authenticatie.

@Order(0)
@Configuration
public class Security extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity web) throws Exception {
        web.authorizeRequests().antMatchers(
                "/v2/api-docs",
                "/configuration/ui",
                "/swagger-resources",
                "/configuration/security",
                "/swagger-ui.html",
                "/webjars/**",
                "/swagger-resources/configuration/ui",
                "/swagger-ui.html"
        )
        .permitAll()
        .and()
        .csrf()
        .disable();
    }
}

Swagger

Vergeet de package niet aan te passen naar deze waarin de RestControllers staan.

@Configuration
@EnableSwagger2
public class Swagger extends WebMvcConfigurationSupport {

    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .securitySchemes(Arrays.asList(new BasicAuth("auth")))
                .protocols(Arrays.asList("https").stream().collect(Collectors.toSet()))
                .select()
                .apis(RequestHandlerSelectors.basePackage("be.zenito.services.unizo.controllers"))
                .paths(PathSelectors.regex("/.*"))
                .build();
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

Output

Nadat je de applicatie gestart hebt kan je dsurfen naar