H'academy
  • H'academy
  • Web
    • Back-end
      • Spring Framework
        • Spring 개발환경 구축
          • Project 생성
          • Maven 설정
          • Maven 저장소 위치 설정
          • Apache Tomcat 연동
          • Lombok 설정
        • Spring MVC Project
          • pom.xml
          • web.xml
          • root-context.xml
          • servlet-context.xml
          • DispatcherServlet
        • Controller
          • File Upload / Download
          • RestController(작성중)
        • Spring Test
          • Assert 단정문
          • Spring 환경 연동 테스트
          • MockMvc Test
        • Spring AOP
          • AOP 용어
          • Pointcut Expression
          • Filter
          • Interceptor
          • Filter vs Interceptor
          • Controller Advice(작성중)
        • Spring JDBC
          • DBCP
          • myBatis
            • ResultMap 활용
        • ETC
          • Logging
            • Tomcat Logging 설정
          • Property 관리
          • E-mail
            • Gmail 변경사항
          • Scheduler
          • Websocket
      • Spring Boot
        • STS 다운로드
        • 프로젝트 생성
        • 프로젝트 구조
        • Spring Devtools
        • Spring Controller
          • JSP 연동
            • * JSP 생성불가 문제
            • Spring Boot 3.x
          • Model
          • 요청 파라미터 처리
          • 경로 변수 처리
          • 요청 메소드
          • Redirect
          • Spring Actuator
        • Spring Boot JDBC
          • Database 정보
          • DAO Pattern
          • ORM Framework
            • myBatis
              • Mapper 생성
            • Spring Data JPA
        • Spring AOP
          • AspectJ
          • Filter
          • Interceptor
          • ControllerAdvice
        • REST API
        • Spring WebSocket
        • Send Mail
        • Logging
        • Spring Boot Test
        • Lombok
      • Java EE
        • 개발환경 구성
          • Server와 Client
          • Web Server와 WAS
        • Dynamic Web Project
      • Apache Tomcat
        • Apache Tomcat 구조
        • Tomcat User 생성
        • Tomcat Manager 설정
      • Maven
      • Jenkins
        • Installation
          • Github Webhook 설정
          • Maven 연동
        • Project setting
          • 소스 코드 관리 설정
          • 빌드 유발 설정
          • 빌드 작업 설정
      • OpenAPI(swagger)
        • swagger 2.x (legacy)
        • swagger 3.x (boot)
        • Swagger UI 꾸미기
        • SpringDoc
    • Front-end
      • HTML
        • Heading
        • <A>
        • <IMG>
        • <DIV>
        • <TABLE>
        • <FORM>
          • <INPUT>
          • <SELECT>
          • <TEXTAREA>
          • <FIELDSET>
        • List
      • CSS
        • CSS 적용 방식
          • 크기(size)
            • 픽셀(px)
          • 색상(color)
        • CSS 선택자
          • 스타일 우선순위
        • CSS 주요 속성
          • 크기 속성
            • border
            • margin
            • padding
            • box-sizing
          • 배경 속성
          • 글자 속성
            • font
            • text
          • 배치 속성
            • position
            • display
            • overflow
            • float
            • flexbox
        • CSS Reset
      • JS
        • syntax
          • let, const
          • 구조 분해 할당
          • spread operator
          • Object copy
          • this
          • module
        • jQuery
          • structure
          • function
          • ajax
            • ajax file upload
        • VueJS
          • CDN(Vue3)
            • 기본 구조
            • Vue Devtools
            • jQuery vs VueJS
            • Vue instance
              • data
                • IME issue
              • v-model
              • template
              • computed
              • watch
                • deep watch
                • vs Computed
              • methods
            • Vue directive
              • v-text
              • v-html
              • v-bind
                • v-bind style
                • v-bind class
              • v-on
                • once
                • prevent
              • v-show
              • v-if
              • v-for
          • Vue-cli 3
            • 프로젝트 구조
            • src
              • main.js
              • App.vue
              • HelloWorld.vue
            • Vue Router 4
              • History mode
              • 404 not found
              • Guard
                • beforeEach
            • Vuex
              • 이동 횟수 측정
            • axios
              • interceptor
          • Vue-electron
        • ReactJS
          • CDN(React18)
            • 템플릿 설명
            • JSX
            • render
            • Handling Events
              • onClick
              • onInput
            • Component
              • 클래스 컴포넌트
                • state
                • props
                • event
                  • Mouse
                  • Input
                • lifecycle
              • 함수형 컴포넌트
                • useState
                • useEffect
                • useReducer
                • useMemo
                • props
                • 조건부 렌더링
          • CRA
            • 자원 경로 설정
            • src 절대 경로 설정
            • react-router
            • Context API
            • Electron 설정
        • Webpack
          • NodeJS
          • Git
    • Ubuntu server
      • Jenkins
    • 테스트 도구
      • JMeter
        • Test Plan
        • Test Plan(with login)
        • Plugin 설치
    • WebRTC
  • Base Language
    • Java
      • Java 실행 과정
        • 개발 환경 구축
        • 샘플 코드 작성
        • 컴파일/실행
        • 환경 변수 설정
      • Java 초급
        • Hello world
        • 자료와 정보
        • 변수
          • 정수
            • 정수의 저장 원리
            • 정수형 변수 생성
          • 실수
            • 실수의 저장 원리
            • 실수형 변수 생성
          • 논리
            • 논리형 변수 생성
          • 문자
          • 문자열
            • 문자열 변수 생성
          • 사용자 정의 자료형
        • 연산자
          • 대입 연산
          • 부호 연산
          • 산술 연산
          • 복합 대입 연산
          • 증감 연산
          • 쉬프트 연산
          • 비트 연산
          • 비교 연산
          • 논리 연산
          • 삼항 연산
          • 변환 연산
        • 표준 입출력
          • 표준 출력
          • 표준 오류 출력
          • 표준 입력
            • Scanner 입력
        • 제어문
          • if 구문
            • 단일 조건
            • 두 가지의 조건
            • 여러 가지의 조건
          • switch~case 구문
          • while 구문
          • do~while 구문
          • for 구문
        • 랜덤(Random)
        • 배열
          • 1차원 배열
          • 2차원 배열
          • 다차원 배열
          • Sort
            • 선택 정렬
            • 버블 정렬
            • 삽입 정렬
      • Java 중급
        • 객체 지향 프로그래밍
        • 클래스
        • 인스턴스
        • 필드
        • 메소드
          • 설정(setter) 메소드
          • 반환(getter) 메소드
        • 생성자
        • 접근 제한
          • private
          • package
          • protected
          • public
        • 정적(static)
        • 불변(final)
        • 상수(constant)
        • 상속
          • this와 super의 이해
          • 멤버 변수 설정
          • 멤버 메소드 설정
          • 생성자 설정
        • 추상화
          • 추상 클래스
          • 인터페이스
        • 다형성
        • 중첩 클래스
          • 일반 중첩 클래스
          • static 중첩 클래스
          • 지역 중첩 클래스
          • 익명 중첩 클래스
      • Java API(작성중)
        • java.lang
        • java.util
        • java.text
        • java.time
        • java.io
        • java.net
        • java.sql
        • java.awt
        • javax.swing
      • Java 고급
        • 제네릭(Generic)
        • 열거형(Enum)
        • Annotation Type
          • Retention
          • Target
          • Nested Annotation
        • Java Reflection
          • Intro
          • Class
          • Field
          • Constructor
          • Method
          • Package
      • JDBC
        • 드라이버 로드
        • 연결 생성
          • JDBC Driver 유형
        • JdbcTemplate
      • Java 버전별 변경사항
        • Java 1.8
          • Lambda Expression
          • Stream API
          • java.time 패키지
        • Java 9
        • Java 12
          • switch~case
        • Java 13
          • Text Block
    • Arduino
      • 학습 준비
        • Reference
        • 아두이노 온라인 시뮬레이터
        • 전기의 이해
        • 그라운드(GND)의 이해
      • 개발 환경 구축
        • CH340 보드 설치
        • Editor 글꼴 설정
      • 아두이노 제어
        • 코드의 구성
        • 시리얼 출력
        • 디지털 출력
          • LED 출력
        • PWM 출력
        • 시리얼 입력
        • 디지털 입력
          • PIR 센서
        • 아날로그 입력
          • 온도 센서(LM35DZ)
          • 조도 센서
          • 가스 센서
        • 피에조 부저
        • 서보 모터 제어
          • 시리얼 서보 모터 제어
          • 스위치 서보 모터 제어
        • 온습도 센서(DHT-11)
        • LCD
      • 아두이노 통신
        • 블루투스(Bluetooth)
          • HC-06
            • 온도 센서 활용
          • HM-10
        • 와이파이(Wi-Fi)
          • ESP-01
            • WiFiEsp 라이브러리 추가
            • WiFiEsp 네트워크 스캔
        • 이더넷(Ethernet)
        • ArduinoJson 라이브리 사용
    • Regular Expression
  • Database
    • Oracle
      • 설치
        • SQL Plus
        • SQL Developer
        • DBeaver
        • Docker(Mac OS)
      • SQL
        • 관리자 명령
          • 사용자 관리
          • 권한 관리
          • Encoding 설정
          • 서비스 포트 설정
        • 사용자 명령
          • 테이블 관리
            • 테이블 항목 제약 조건
            • 외래키 제약조건
            • 데이터 유형
          • 시퀀스 관리
          • 데이터 관리
            • 데이터 추가
            • 데이터 조회
              • 오라클 내장 함수
              • 그룹 조회
              • Top N Query
            • 데이터 수정
            • 데이터 삭제
          • 뷰 관리
          • 인덱스 관리
          • 집합 연산
          • 테이블 조인
            • 등가 조인
            • 외부 조인
        • HR 계정
        • 기타 명령
          • 컬럼 간격 조정
      • 내보내기 및 불러오기
        • EXPDP, IMPDP
        • Docker로 실행중인 경우
      • 기타
        • 자동 세션 제거
        • Tablespace 관리
        • Unlock user
  • 면접대비
    • Q&A
      • Java
      • Database
      • Web
      • IT 일반상식
  • ETC
    • Eclipse IDE
      • 설치
      • 화면 설명
      • 환경 설정
      • 프로젝트 생성
      • 소스파일 작성 및 실행
    • Github
      • Github 계정 관리
      • Github 저장소 관리
        • Profile
        • Collaborators
        • Code
        • Issues
        • Pull requests
        • Action
          • Vue 3 Deploy Action
      • Personal Access Token
      • Git ignore 설정
        • Spring 개발용 샘플
      • Github Eclipse 연동
        • Branches
        • Project
        • Team project
          • Dynamic web project
          • Spring Boot Project
          • Branch 생성
          • Pull Request
          • Branch 보호
          • Branch 다시 생성
    • Figma
      • Team
      • Design
      • Component
    • 과정평가형
      • 실기 모의고사 1회
      • 실기 모의고사 2회
      • 실기 모의고사 3회
      • 실기 모의고사 4회
    • VScode
      • Live Server 실행 오류
      • Github 계정 변경
    • Naver ToastUI Editor
      • Editor 만들기
        • Editor options
          • File upload
      • Viewer 만들기
    • 문자 인코딩 방식
    • OBS
      • 녹화 잡음 제거 설정
    • Semantic Version
Powered by GitBook
On this page
  • Springfox-swagger 2
  • 프로젝트 생성
  • pom.xml 설정
  • Controller 생성
  • Swagger Configuration
  • 기본 옵션 설정
  • 커스텀 옵션 설정
  • Swagger-UI 설정
  1. Web
  2. Back-end
  3. OpenAPI(swagger)

swagger 2.x (legacy)

PreviousOpenAPI(swagger)Nextswagger 3.x (boot)

Last updated 2 years ago

Springfox-swagger 2

이 문서에서는 Spring MVC Project에 swagger 2.x를 적용하는 과정에 대해서 다룬다.

프로젝트 생성

프로젝트는 Spring MVC Project로 생성한다. Spring STS 4에서 보이지 않을 경우 추가 플러그인 설치가 필요하다.

pom.xml 설정

pom.xml에서 프로젝트를 설정한다.

  • Java 11

  • Spring 5.3.20

  • 의존성 추가

    • com.faxterxml.jackson.core.jackson-databind (2.13.3)

    • io.springfox.springfox-swagger2 (2.9.2)

    • io.springfox.springfox-swagger-ui (2.9.2)

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/maven-v4_0_0.xsd">
	
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hacademy</groupId>
	<artifactId>swagger</artifactId>
	<name>spring-legacy-swagger</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	
	<properties>
		<java-version>11</java-version>
		<org.springframework-version>5.3.20</org.springframework-version>
		<org.aspectj-version>1.9.9.1</org.aspectj-version>
		<org.slf4j-version>1.7.36</org.slf4j-version>
	</properties>
	
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>        
		
		<dependency>
		    <groupId>com.fasterxml.jackson.core</groupId>
		    <artifactId>jackson-databind</artifactId>
		    <version>2.13.3</version>
		</dependency>
		<dependency>
		    <groupId>io.springfox</groupId>
		    <artifactId>springfox-swagger2</artifactId>
		    <version>2.9.2</version>
		</dependency>
		<dependency>
		    <groupId>io.springfox</groupId>
		    <artifactId>springfox-swagger-ui</artifactId>
		    <version>2.9.2</version>
		</dependency>
		
	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>${java-version}</source>
                    <target>${java-version}</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Controller 생성

테스트를 위한 @RestController를 생성한다.

  • 패키지 - com.hacademy.swagger.controller

  • 클래스 - ExampleController

@RestController
public class ExampleController {
	
	@GetMapping("/")
	public String home() {
		return "home";
	}
	
	@GetMapping("/test")
	public String test() {
		return "test";
	}
	
}

Swagger Configuration

Swagger Configuration을 추가하면 기본 설정이 완료된다. 설정을 추가하는 방법은 두 가지가 있다.

  1. 기본 옵션 설정 사용 (Swagger2DocumentationConfiguration)

  2. 커스텀 옵션 설정 사용 (직접 생성)

둘 다 servlet-context.xml에 등록한다.

설정이 완료되면 다음 주소에서 프로젝트 분석 결과를 확인할 수 있다.

  • {protocol}://{host}:{port}/{context-path}/v2/api-docs

기본 옵션 설정

servlet.context.xml
<beans:bean id="swagger2Config" class="springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration"></beans:bean>

커스텀 옵션 설정

servlet.context.xml
<beans:bean id="swagger2Config" class="com.hacademy.swagger.configuration.SwaggerCustomConfiguration"></beans:bean>
  • 패키지 - com.hacademy.swagger.configuration

  • 클래스 - SwaggerCustomConfiguration

@EnableSwagger2
public class SwaggerCustomConfiguration {
	
	@Bean
	public Docket customApi() {
		return new Docket(DocumentationType.SWAGGER_2)
				.select()
					.apis(RequestHandlerSelectors.any())
					.paths(PathSelectors.any())
				.build();
	}
	
}

커스텀 클래스의 경우 추가 설정 없이 기본 설정으로만 작성하였다.

Swagger-UI 설정

swagger는 내부적으로 webjar를 사용하며, 자체 html 페이지를 가지고 있다. 이는 springfox-swagger-ui 의존성을 열어서 확인할 수 있다.

이 중에서 swagger-ui.html은 자동 생성될 문서의 내용이며, webjars에 포함되어 있는 요소들은 자동 생성될 문서의 의존 라이브러리이다. 따라서 다음 요소들은 접근이 가능하도록 설정한다.

  • swagger-ui.html

  • /webjars/**

servlet.context.xml
<resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"></resources>
<resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"></resources>

설정을 마친 후 서버를 재시작하고 다음 주소로 접속한다.

  • {protocol}://{host}:{port}/{context-path}/swagger-ui.html

다음과 같은 화면이 나오면 설정이 정상적으로 이루어진 것이다.

swagger 3는 2와 주소가 다르다

  • swagger 2 - {protocol}://{host}:{port}/{context-path}/swagger-ui.html

  • swagger 3 - {protocol}://{host}:{port}/{context-path}/swagger-ui/index.html

따라서 허용해야 하는 주소가 다르다.

Spring Legacy Project 선택
Spring MVC Project를 선택한다
top-level package를 설정한다.
springfox-swagger-ui 의존성 내부 구조