- 添加Swagger2依赖
<!-- swagger-mvc -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.7</version>
</dependency>
<!-- swagger-mvc -->
2.创建Swagger2的配置类
@EnableWebMvc
@EnableSwagger2
/*@ComponentScan(basePackages = {"com.test"}) */
@Configuration
public class RestApiConfig extends WebMvcConfigurationSupport{
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.test"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring 中使用Swagger2构建RESTful APIs")
.termsOfServiceUrl("http://blog.csdn.net/he90227")
.contact("郭敬仰")
.version("1.0")
.build();
}
}
3.
<!-- 开启springmvc静态资源文件支持 -->
<mvc:default-servlet-handler />
4.确保swagger2配置类被扫描到(假如RestApiConfig类在com.test目录下 )
<context:component-scan base-package="com.test" />
5.
controller的配置,这里我只做简单的配置测试swagger是否正常工作
@Controller
@RequestMapping("/user")
@Api(value = "/user", tags = "User接口")
public class UserController {
private static Logger logger = Logger.getLogger(UserController.class);
@Autowired
private UserService userService;
@RequestMapping(value = "/getUser/{id}",method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "根据id获取用户信息", notes = "根据id获取用户信息", httpMethod = "GET", response = User.class)
public ResponseEntity<User> getUser(@PathVariable int id){
User user = userService.getUserById(id);
logger.info("controller:"+user);
return ResponseEntity.ok(user);
}
}
访问地址:[项目访问地址]/swagger-ui.html
例如本地Tomcat运行swagger-demo,那么访问地址为:http://localhost:8080/swagger-demo/swagger-ui.html