springboot 集成 swagger2 小记

环境:
springboot 1.5.8.RELEASE

程序员话比较少,直接上代码来的实际。

新建swagger配置

@Configuration
class 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
@EnableWebMvc
public 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功能


...
@EnableSwagger2
public 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();
        }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值