728x90
package com.danal.snack.swagger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableWebMvc
// 접속 url : http://localhost:8080/swagger-ui/index.html
public class SwaggerConfig implements WebMvcConfigurer {
/**
* Swagger를 위한 Docket 빈을 추가한다.
*
* @return
*/
@Bean
public Docket api() {
final ApiInfo apiInfo = new ApiInfoBuilder()
.title("STUDIT REST API")
.description("<h3>STUDIT에서 사용되는 RestApi에 대한 문서를 제공한다.</h3>")
.contact(new Contact("STUDIT", "https://studit.com", "studit@studit.com"))
.license("MIT License")
.version("1.01")
.build();
return new Docket(DocumentationType.SWAGGER_2)
.ignoredParameterTypes(Errors.class)// Swagger 2.0 기반의 문서 작성
.apiInfo(apiInfo) // 문서에 대한 정보를 설정한다.
.select() // ApiSelectorBuilder를 반환하며 상세한 설정 처리
.apis(RequestHandlerSelectors.basePackage("com.danal.snack"))// 대상으로하는 api 설정
.paths(PathSelectors.any())
.build(); // Docket 객체 생성
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
}
}
springfox-swagger2, springfox-swagger-ui, jackson-databind 설치
버전
SwaggerConfig 등록
package com.ssafy.ws.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
//@EnableWebMvc//스프링 부트에서는 X(무조건),스프링에서는 필수!
public class Swagger2Config implements WebMvcConfigurer {
/**
* Swagger를 위한 Docket 빈을 추가한다.
*
* @return
*/
@Bean
public Docket api() {
final ApiInfo apiInfo = new ApiInfoBuilder()
.title("SSAFY 도서관리 API")
.description("<h3>워크샵에서 사용되는 RestApi에 대한 문서를 제공한다.</h3>")
.contact(new Contact("SSAFY", "https://edu.ssafy.com", "ssafy@ssafy.com"))
.license("MIT License")
.version("1.01")
.build();
return new Docket(DocumentationType.SWAGGER_2) // Swagger 2.0 기반의 문서 작성
.apiInfo(apiInfo) // 문서에 대한 정보를 설정한다.
.select() // ApiSelectorBuilder를 반환하며 상세한 설정 처리
.apis(RequestHandlerSelectors.basePackage("com.ssafy.ws.controller"))// 대상으로하는 api 설정
.paths(PathSelectors.ant("/**/bookapi/**")) // controller에서 swagger를 지정할 대상 path 설정
.build(); // Docket 객체 생성
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
}
}
설정 해준 컨트롤러에 RestController 작성
package com.ssafy.ws.controller;
import java.lang.System.Logger;
import java.util.List;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ssafy.ws.model.dto.Book;
import com.ssafy.ws.model.dto.SearchCondition;
import com.ssafy.ws.model.service.BookService;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/bookapi/2")
@CrossOrigin("*")
public class BookRestController {
@Autowired
BookService bookService;
@ApiOperation(value = "조건에 맞는 도서 목록 반환",response = Book.class)
@GetMapping("/book/{id}")
public ResponseEntity<?> select(@PathVariable String id){
try {
Book book = bookService.select(id);
if(book !=null) {
return new ResponseEntity<Book>(book,HttpStatus.OK);
}
else {
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
} catch (Exception e) {
return exceptionHandling(e);
}
}
@GetMapping("/book")
@ApiOperation(value = "조건에 맞는 도서 목록 반환",response = Book.class)
public ResponseEntity<?> select(@ModelAttribute SearchCondition condition){
try {
List<Book> books = bookService.search(condition);
if(books!=null && books.size()>0) {
return new ResponseEntity<List<Book>>(books,HttpStatus.OK);
}
else {
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
} catch (Exception e) {
return null;
}
}
@PostMapping("/book")
@ApiOperation(value = "객체 저장함",response = Integer.class)
public ResponseEntity<?> insert(Book book){
try {
bookService.insert(book);
int result=1;
return new ResponseEntity<Integer>(result,HttpStatus.CREATED);
} catch (Exception e) {
return exceptionHandling(e);
}
}
@PutMapping("/book")
@ApiOperation(value = "Book 객체 수정함",response = Integer.class, notes = "객체를 수정합니다")
public ResponseEntity<?> update(Book book){
try {
bookService.update(book);
int result=0;
if(result==0) {
return new ResponseEntity<Integer>(result,HttpStatus.NO_CONTENT);
}
else {
return new ResponseEntity<Integer>(result,HttpStatus.CREATED);
}
} catch (Exception e) {
return exceptionHandling(e);
}
}
@ApiOperation(value = "Book 객체 삭제",response = Integer.class, notes = "기록을 삭제합니다.")
@DeleteMapping("/book/{id}")
public ResponseEntity<?> delete(@PathVariable Integer id){
try {
bookService.delete(id);
int result = 0;
if(result==0) {
return new ResponseEntity<Integer>(result,HttpStatus.NO_CONTENT);
}
else {
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
} catch (Exception e) {
return exceptionHandling(e);
}
}
public ResponseEntity<String> exceptionHandling(Exception e){
e.printStackTrace();
return new ResponseEntity<String>("미안 : "+e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
}
}
http://localhost:8080/ws/swagger-ui/index.html
접속
스프링 부트에서 설정
그레들 추가
implementation("io.springfox:springfox-boot-starter:3.0.0")
implementation("io.springfox:springfox-swagger-ui:3.0.0")
Config 파일
package com.danal.snack.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
@EnableWebMvc
public class SwaggerConfig implements WebMvcConfigurer {
/**
* Swagger를 위한 Docket 빈을 추가한다.
*
* @return
*/
@Bean
public Docket api() {
final ApiInfo apiInfo = new ApiInfoBuilder()
.title("SSAFY 도서관리 API")
.description("<h3>워크샵에서 사용되는 RestApi에 대한 문서를 제공한다.</h3>")
.contact(new Contact("SSAFY", "https://edu.ssafy.com", "ssafy@ssafy.com"))
.license("MIT License")
.version("1.01")
.build();
return new Docket(DocumentationType.SWAGGER_2) // Swagger 2.0 기반의 문서 작성
.apiInfo(apiInfo) // 문서에 대한 정보를 설정한다.
.select() // ApiSelectorBuilder를 반환하며 상세한 설정 처리
.apis(RequestHandlerSelectors.basePackage("com.danal.snack"))// 대상으로하는 api 설정
.paths(PathSelectors.any()) // controller에서 swagger를 지정할 대상 path 설정)
.build(); // Docket 객체 생성
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
}
}
728x90
'백엔드 > Spring(Boot)' 카테고리의 다른 글
스프링 AOP 포인트 컷 외부 설정 (0) | 2021.11.03 |
---|---|
스프링 AOP 순서 설정 (0) | 2021.11.03 |
스프링 초기화 샘플 데이터 입력 (0) | 2021.10.18 |
스프링 API 리스트 전송 방법 (0) | 2021.10.18 |
스프링 파일 업로드 (0) | 2021.10.15 |