프로젝트를 진행하면서 백엔드 api 테스트를 위해 swagger 템플릿을 적용하려고 한다. 이전 프로젝트에서 swagger를 통해서 백엔드 api 테스트를 진행했었는데 매우 편리했던 기억이 있어서 이번 프로젝트에서도 적용해보려고 한다. 이전 프로젝트에서는 적용된 것을 사용해봤다면 이번 프로젝트에서는 내가 직접 프로젝트에 적용시켜보려고 한다.
1. config 폴더에 swagger관련 설정 파일을 작성한다.
- SwaggerConfig -> Swagger API 문서 기본 설정
@Configuration
@EnableWebMvc
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.moodtree"))
.paths(PathSelectors.ant("/**"))
.build();
}
}
@EnableWebMvc : Spring MVC 활성화 (Swagger가 MVC 기능 사용)
@EnableSwagger2 : Swagger 기능 켜기
Docket Bean : Swagger UI가 어떤 API를 문서화할지 지정
basePackage : 스캔할 Controller 패키지 범위 지정
PathSelectors : 문서화할 URI 범위 지정
- WebConfig -> MVC 설정 + Swagger 정적 리소스 매핑
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.moodtree")
// 트랜잭션 관리 활성화 (스웨거 템플릿)
@EnableTransactionManagement
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/views/", ".jsp");
}
// 정적리소스 처리 (스프링이 아니라 톰캣이 처리) 활성화
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer config) {
config.enable();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//Swagger UI 화면을 불러오는 핵심 부분
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
}
}
configureViewResolvers : JSP 뷰 매핑 설정
configureDefaultServletHandling : 정적 리소스 톰캣이 처리
addResourceHandlers : Swagger UI 리소스 경로 열어줌 (Swagger UI 화면을 불러오는 핵심)
2. Controller 폴더에 Swagger 컨트롤러 작성
- HomeController 작성 -> Swagger에서 테스트할 API
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
@Api(tags = "스웨거 테스트용 컨트롤러")
@RestController
@RequestMapping("/swagger")// json 방식으로 응답
public class HomeController {
@ApiOperation("Get 테스트")
@GetMapping
public String home() {
return "hello";
}
@ApiOperation("POST 테스트")
@PostMapping
public String testPost(@RequestBody String message) {
return "받은 메시지: " + message;
}
}
@Api : Swagger 문서 그룹 이름
@ApiOperation : API 설명 출력
@RestController : JSON 반환
/swagger : Swagger UI에서 호출할 Endpoint
3. servlet-context.xml에 swagger 관련 설정들 작성
- Swagger UI 자원 경로 추가
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="classpath:/META-INF/resources/" />
<resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"></resources>
<resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"></resources>
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.moodtree" />
<annotation-driven />
<!-- JSON 한글 깨짐 방지 -->
<annotation-driven>
<message-converters>
<beans:bean class="org.springframework.http.converter.StringHttpMessageConverter">
<beans:property name="supportedMediaTypes">
<beans:list>
<beans:value>text/plain;charset=UTF-8</beans:value>
<beans:value>application/json;charset=UTF-8</beans:value>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<beans:property name="defaultCharset" value="UTF-8"/>
</beans:bean>
</message-converters>
</annotation-driven>
</beans:beans>
4. root-context.xml에 swagger관련 설정들 작성
- 전역 Bean 설정
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
</beans>