순서

  1. pom.xml에서 swagger 받기
  2. WebMvcContextConfiguration.java ( WebMvcConfigurerAdapter implement file)에 addResourceHandlers메서드에
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

3. SwaggerConfig 파일 만들고

@Bean
	public Docket api() {
		return new Docket(DocumentationType.SWAGGER_2)
				.select()
				.apis(RequestHandlerSelectors.basePackage("kr.or.connect.reservation.controller"))
				.paths(PathSelectors.any())
				.build()
				.apiInfo(apiInfo());
				
	}

	ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("NaverBoostCourse Reservation REST API")
            .description("It is a RESTful API for providing information by reservation.")
            .license("")
            .licenseUrl("http://unlicense.org")
            .termsOfServiceUrl("")
            .version("0.1")
            .contact(new Contact("","", ""))
            .build();
    }

4. RestController (api반환해주는) 컨트롤러 있어야함

 

pom.xml

더보기

 

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>kr.or.connect</groupId>
	<artifactId>reservation</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>reservation Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<spring.version>4.3.5.RELEASE</spring.version>
		<!-- jackson -->
		<jackson2.version>2.8.6</jackson2.version>
		<springfox.swagger2.version>2.9.2</springfox.swagger2.version>  -> 여기!
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		

		<!-- Servlet JSP JSTL -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- spring jdbc & jdbc driver & connection pool -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.21</version>
		</dependency>

		<!-- basic data source -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>2.1.1</version>
		</dependency>

		<!-- Jackson Module -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson2.version}</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.datatype</groupId>
			<artifactId>jackson-datatype-jdk8</artifactId>
			<version>${jackson2.version}</version>
		</dependency>

		<!-- swagger -->        -> 여기!
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>${springfox.swagger2.version}</version>
		</dependency>

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>${springfox.swagger2.version}</version>
		</dependency>

		<!-- log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
	</dependencies>
	<!-- FOR JAVA 1.8 -->
	<build>
		<finalName>reservation</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.6.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

WebMvcContextConfiguration

더보기

 

package kr.or.connect.reservation.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableWebMvc
@EnableSwagger2
@ComponentScan(basePackages = { "kr.or.connect.reservation.controller" })
@Import(SwaggerConfig.class)
public class WebMvcContextConfiguration extends WebMvcConfigurerAdapter{

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
		registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
		registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
		// swagger 관련 리소스 등록
		registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
	}

	// default servlet handler를 사용하게 합니다.
	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}

	@Override
	public void addViewControllers(final ViewControllerRegistry registry) {
		System.out.println("addViewControllers가 호출됩니다. ");
		registry.addViewController("/").setViewName("index");
	}

	@Bean
	public InternalResourceViewResolver getInternalResourceViewResolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("/WEB-INF/views/");
		resolver.setSuffix(".jsp");
		return resolver;
	}
}

 

SwaggerConfig

더보기

 

package kr.or.connect.reservation.config;

import java.util.HashSet;
import java.util.Set;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

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
@EnableWebMvc
@EnableSwagger2
public class SwaggerConfig {

	@Bean
	public Docket api() {
		return new Docket(DocumentationType.SWAGGER_2)
				.consumes(getProduceContentTypes())
				.select()
				.apis(RequestHandlerSelectors.basePackage("kr.or.connect.reservation.controller"))
				.paths(PathSelectors.any())
				.build()
				.apiInfo(apiInfo());
				
	}
	
	 private Set<String> getProduceContentTypes() {
	        Set<String> produces = new HashSet<>();
	        produces.add("*/*");
	        return produces;
	    }

	ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("NaverBoostCourse Reservation REST API")
            .description("It is a RESTful API for providing information by reservation.")
            .license("")
            .licenseUrl("http://unlicense.org")
            .termsOfServiceUrl("")
            .version("0.1")
            .contact(new Contact("","", ""))
            .build();
    }
}

 

ReservationApiController(@RestController)

더보기

 

package kr.or.connect.reservation.controller;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.annotation.JsonFormat;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import kr.or.connect.reservation.dto.Category;
import kr.or.connect.reservation.dto.CategoryResponse;
import kr.or.connect.reservation.dto.DisplayInfoResponse;
import kr.or.connect.reservation.dto.Product;
import kr.or.connect.reservation.dto.ProductResponse;
import kr.or.connect.reservation.dto.Promotion;
import kr.or.connect.reservation.dto.PromotionResponse;
import kr.or.connect.reservation.dto.ReservationInfo;
import kr.or.connect.reservation.dto.ReservationInfoResponse;
import kr.or.connect.reservation.dto.ReservationParam;
import kr.or.connect.reservation.dto.ReservationResponse;
import kr.or.connect.reservation.service.DetailService;
import kr.or.connect.reservation.service.MainPageService;
import kr.or.connect.reservation.service.ReservationService;

@Api(description="모든 명세", tags="all")
@RestController
@RequestMapping(path="/api")
public class ReservationApiController {
	
	@Autowired
	MainPageService mainpageService;
	
	@Autowired
	DetailService detailService;
	
	@Autowired
	ReservationService reservationService;
	
	@ApiOperation(response=Product.class, value="상품 목록 구하기")
	@GetMapping(path = "/products", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String, Object> productList(@RequestParam(name="categoryId", required=false, defaultValue="0") int categoryId,
			@RequestParam(name="start", required=false, defaultValue="0") int start) {
		
		ProductResponse products = new ProductResponse();
		
		if(categoryId == 0){
			products = mainpageService.getProducts(categoryId +1 , start);
		}
		else {
			products = mainpageService.getProducts(categoryId, start);
		}
		
		Map<String, Object> map = new HashMap<>();
		
		if(products.getItems().isEmpty()) {}
		else {
			map.put("totalCount", products.getTotalCount());
			map.put("items", products.getItems());
			map.put("morebtn", "morebtn");
		}
		return map;
	} 
	@ApiOperation(response=Category.class, value="카테고리 정보")
	@GetMapping("/categories")
	@ResponseBody
	public CategoryResponse categoryList(){
		CategoryResponse categoryResponse = mainpageService.getCategories();
		return categoryResponse;
	}
	
	@ApiOperation(response=Promotion.class, value="프로모션 정보")
	@GetMapping("/promotions")
	@ResponseBody
	public PromotionResponse promotionList() {
		PromotionResponse promotion_list = mainpageService.getPromotions();
		return promotion_list;
	}
	
	@ApiOperation(response=DisplayInfoResponse.class, value="상품 전시 정보 구하기")
	@GetMapping(path = "/products/{displayInfoId}", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String, Object> detail(@PathVariable int displayInfoId) {
		
		DisplayInfoResponse displayInfoResponse = detailService.getDisplayInfoResponse(displayInfoId);
		Map<String, Object> map = new HashMap<>();
		map.put("displayInfo", displayInfoResponse.getDisplayInfo());  
		map.put("productImages", displayInfoResponse.getProductImages());
		map.put("displayInfoImage", displayInfoResponse.getDisplayInfoImage());
		map.put("comments", displayInfoResponse.getComments());
		map.put("averageScore", (Double)displayInfoResponse.getAverageScore());    
		map.put("productPrices", displayInfoResponse.getProductPrices());   
		return map;
	} 
	
	@ApiOperation(response=ReservationInfoResponse.class, value="예약 정보 조회")
	@GetMapping("/myreservation")
	public String myreservePage(
			@ApiParam (value="reservationEmail", required=true)
			@RequestParam String reservationEmail, ModelMap model) {
		
		ReservationInfoResponse reservationInfoResponse = reservationService.getReservationInfo(reservationEmail);
		model.addAttribute("reservationInfoResponse", reservationInfoResponse);
		return "myreservation";
	}
	
	
	@ApiOperation(value="예약 하기")
	@PostMapping(path = "/reserve")
	public ReservationResponse setReservations(
		@ApiParam (value="예약하기 Request Body 모델", required=true) 
		@RequestBody  ReservationParam param){
		return reservationService.setReservation(param);
	}
	
	@ApiOperation(response=ReservationResponse.class, value="예약 취소하기")
	@PutMapping(value = "/cancleReservation/{reservationInfoId}")
	@ResponseBody
	public ReservationResponse cancleReservation(@PathVariable(name = "reservationInfoId") Integer reservationInfoId) {
		ReservationResponse reservationResponse = reservationService.apicancelReservation(reservationInfoId);
		return reservationResponse; 	
	}
	
	
}

 

 

Spring SwaggerConfiguration JavaConfig example

 

Spring SwaggerConfiguration JavaConfig example

Spring SwaggerConfiguration JavaConfig example. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com