环境:
springboot 1.5.8.RELEASE程序员话比较少,直接上代码来的实际。
新建swagger配置
@Configurationclass SwaggerConfig { /** * 为了在生产环境中不启用swagger,此处需要读取配置文件中的配置 */ @Value("${swagger.enable}") private Boolean enable; @Bean public Docket myApi() { return new Docket(DocumentationType.SWAGGER_2) .enable(enable) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.changan.carbond.rest")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title(" 此处填写 生成文档的标题 ") .description(" 此处填写 生成文档的描述 ") .version("1.0") .build(); }}
定义swagger文件的处理路由
@Configuration@EnableWebMvcpublic class WebMvcConfig 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/"); }}
开启swagger功能
...@EnableSwagger2public class Application extends SpringBootServletInitializer { public static void main(String[] args) { ... }}
spring-security还有话说
如果集成了spring-security 可能还需要添加一下配置进行权限控制
@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true)public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String[] AUTH_WHITELIST = { // -- swagger ui "/swagger-resources/**", "/v2/api-docs", "/webjars/**", }; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.antMatcher("/**") .authorizeRequests() .antMatchers(AUTH_WHITELIST).permitAll() .anyRequest().authenticated(); }}