ΰ­¨β”ˆβ”ˆβ”ˆ Web β”ˆβ”ˆβ”ˆΰ­§/β†˜ SpringBoot

[SpringBoot] Swagger μ„€μ •ν•˜κΈ°

λΉ΅λΉ΅μƒˆ 2021. 3. 16. 20:30

 

dependency μΆ”κ°€

λ¨Όμ € μŠ€μ›¨κ±° λ””νŽœλ˜μ‹œλ₯Ό μΆ”κ°€ν•œλ‹€. build.gradle νŒŒμΌμ— 라이브러리λ₯Ό μΆ”κ°€ν•΄μ€€λ‹€.

ν•„μš”ν•œ 라이브러리의 λ””νŽœλ˜μ‹œλŠ” ν•˜μœ„ λ§ν¬μ—μ„œ μ‰½κ²Œ 찾을 수 μžˆλ‹€.

https://mvnrepository.com/artifact/io.springfox/springfox-swagger2/2.9.2

 

Maven Repository: io.springfox » springfox-swagger2 » 2.9.2

 

mvnrepository.com

...
repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-aop'
    implementation 'org.springframework.kafka:spring-kafka'
    implementation 'org.projectlombok:lombok'
    // swagger
    implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.6.1'
    implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.1'
    testImplementation 'org.springframework.kafka:spring-kafka-test'
}
...

// swagger λ°‘μ˜ 두 쀄을 μž…λ ₯ν•΄μ£Όκ³ , Load Gradle Changesλ₯Ό ν•΄μ€€λ‹€.

swagger-uiλŠ” μŠ€μ›¨κ±°κ°€ μƒμ„±ν•˜λŠ” API λ¬Έμ„œλ₯Ό μ‚¬μš©μž λŒ€ν™”λ°©μ‹μœΌλ‘œ 더 μ‰½κ²Œ λ§Œλ“€μ–΄ μ£ΌλŠ” λ‚΄μž₯ μ†”λ£¨μ…˜μ΄λ‹€.

 

SwaggerConfig.java 파일 생성

package com.kiwius.kafka.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).select()
                .apis(RequestHandlerSelectors.basePackage("com.kiwius.kafka")).paths(PathSelectors.any())
                .build();
    }
}
  • @Configuration μ–΄λ…Έν…Œμ΄μ…˜
    μŠ€ν”„λ§ IOC Containerμ—κ²Œ ν•΄λ‹Ή 클래슀λ₯Ό Bean ꡬ성 ν΄λž˜μŠ€μž„μ„ μ•Œλ €μ€€λ‹€.
  • @Bean μ–΄λ…Έν…Œμ΄μ…˜
    @Component μ–΄λ…Έν…Œμ΄μ…˜ λ‘˜ λ‹€ IOC Container에 Bean을 λ“±λ‘ν•˜λ„λ‘ ν•˜λŠ” 메타데이터λ₯Ό κΈ°μž…ν•˜λŠ” μ–΄λ…Έν…Œμ΄μ…˜μ΄λ‹€.
    λ‹€λ₯Έ 점은 @Bean은 κ°œλ°œμžκ°€ 직접 μ œμ–΄κ°€ λΆˆκ°€λŠ₯ν•œ μ™ΈλΆ€ 라이브러리 등을 Bean으둜 λ§Œλ“€ λ•Œ μ‚¬μš©ν•œλ‹€.
    λ°˜λŒ€λ‘œ @ComponentλŠ” κ°œλ°œμžκ°€ 직접 μž‘μ„±ν•œ 클래슀λ₯Ό Bean으둜 등둝할 λ•Œ μ‚¬μš©ν•œλ‹€.
  • ν•΄λ‹Ή config νŒŒμΌμ„ 톡해 basePackage ν•˜μœ„μ˜ Rest APIκ°€ Swaggerλ₯Ό 톡해 κ΄€λ¦¬λœλ‹€.

 

swagger-ui.html 접속

  • http://localhost:8080/swagger-ui.html에 접속해 ν™•μΈν•œλ‹€.