最近项目里要用到SpringBoot + swagger,查了其他小伙伴们的资料,或多或少有点问题,在此我再梳理一遍。
1、maven依赖
org.springframework.boot
spring-boot-starter-parent
2.1.10.RELEASE
com.alibaba
fastjson
1.2.62
com.ctrip.framework.apollo
apollo-client
1.4.0
guava
com.google.guava
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-amqp
org.projectlombok
lombok
1.16.20
provided
com.google.guava
guava
23.0
org.apache.commons
commons-lang3
3.9
commons-codec
commons-codec
1.13
org.apache.commons
commons-text
1.8
org.apache.httpcomponents
httpclient
4.5.10
commons-codec
commons-codec
mysql
mysql-connector-java
commons-collections
commons-collections
3.2.2
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
org.apache.commons
commons-dbcp2
2.4.0
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
org.powermock
powermock-api-mockito2
2.0.4
test
org.powermock
powermock-module-junit4
2.0.4
test
org.springframework
spring-test
test
org.mybatis.spring.boot
mybatis-spring-boot-starter-test
1.3.2
test
2、配置swagger,让swagger加载起来
@Configuration
@EnableSwagger2
//配置在哪些环境启用swagger,好用。一般情况下在生产环境,用禁用swagger的。对应pom.xml中的 profiles配置
@Profile({"dev","fat","uat","pro"})
public class SwaggerConfig extends WebMvcConfigurationSupport{
@Bean
public Docket createRestApi () {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("xxxx")
.select()
.apis(RequestHandlerSelectors.basePackage("com.yunda.data.controller"))
.paths(PathSelectors.any())
.build().apiInfo(getApiInfo());
}
private ApiInfo getApiInfo(){
return new ApiInfoBuilder()
.title("dsync-dispatcher api")
.description("xxxx api")
.version("1.0.0")
.contact(new Contact("suyujun", "", "[email protected]"))
.build();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//这些配置要有,我遇到了如果不配置,swagger一直是 404的问题
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
// 解决 SWAGGER 404报错
registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
3.springboot启动主类
@SpringBootApplication
@EnableApolloConfig
@EnableRabbit
@ImportResource
@MapperScan(basePackages = {"xxxx.xxxx.xxxx"})
public class DsyncDispatcherApplication extends WebMvcConfigurationSupport {
private static final Logger LOGGER = LoggerFactory.getLogger(DsyncDispatcherApplication.class);
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(DsyncDispatcherApplication.class, args);
ApplicationContextUtils.setApplicationContext(applicationContext);
}
}