스웨거는 API 문서를 자동화 해줍니다! 개꿀....
그뿐만 아니라 웹 UI를 이용해 테스트도 진행 가능합니다!
pom.xml에 다음과 같이 추가해줍니다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
package com.corini.springbootswagger.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.any())
.paths(PathSelectors.ant("/api/**"))
.build();
}
}
package com.corini.springbootswagger.account;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
@Getter
@Setter
@ToString
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Account {
@Id
@GeneratedValue
private Long id;
private String username;
private String password;
@Builder
public Account(String username, String password) {
this.username = username;
this.password = password;
}
}
package com.corini.springbootswagger.account;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AccountRepository extends JpaRepository<Account, Long> {
}
package com.corini.springbootswagger.account;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RestController
@AllArgsConstructor
@RequestMapping(value = "/api")
public class AccountController {
private AccountRepository accountRepository;
@GetMapping("/accounts")
public Object getAccountList() {
return accountRepository.findAll();
}
@GetMapping("/account/{id}")
public Object getAccountById(@PathVariable("id") Long id) {
return accountRepository.findById(id);
}
@DeleteMapping("/account/{id}")
public Object delAccountById(@PathVariable("id") Long id) {
accountRepository.deleteById(id);
return accountRepository.findAll();
}
@PostMapping("/account")
public void saveAccount(@RequestBody AccountSaveRequestDto dto) {
accountRepository.save(dto.toEntity());
}
}
http://localhost:8080/swagger-ui.html 에서 확인 가능합니다.
문서 확인 뿐만 아니라 get
, post
, delete
, put
메소드를 이용한 테스트도 진행이 가능합니다.