Red Hat Training
A Red Hat training course is available for Red Hat Fuse
54장. Swagger 지원을 사용하여 JAX-RS 엔드 포인트 확장
초록
CXF Swagger2Feature(org.apache.cxf.jaxrs.swagger.Swagger2Feature)를 사용하면 간단한 구성으로 게시된 JAX-RS 서비스 끝점을 확장하여 Swagger 2.0 문서를 생성할 수 있습니다.
Swagger2Feature는 Spring Boot 및 Karaf 구현 모두에서 지원됩니다.
54.1. Swagger2Feature options
Swagger2Feature에서 다음 옵션을 사용할 수 있습니다.
표 54.1. Swagger2기능 작업
| 이름 | 설명 | 기본값 |
|---|---|---|
|
|
컨텍스트 루트 경로 + ( | null |
|
| 연락처 정보 + | |
|
| 설명 + | "애플리케이션" |
|
| 보안 필터 + | null |
|
| 호스트 및 포트 정보 + | null |
|
|
모든 리소스를 스캔할 때 특정 경로 제외 ( | null |
|
| 라이센스 + | "Apache 2.0 라이센스" |
|
| 라이센스 URL+ | |
|
|
| false |
|
| 리소스를 검색해야 하는 쉼표로 구분된 패키지 이름 목록입니다. | 끝점에서 구성된 서비스 클래스 목록입니다. |
|
| 필터로 기능 실행 | false |
|
| swagger 문서 생성+ | true |
|
|
비 주석 처리된 JAX-RS 리소스를 포함한 모든 리소스를 스캔합니다( | false |
|
| 프로토콜 체계 + | null |
|
| Swagger UI 구성 | null |
|
| 서비스 URL 추가 | null |
|
| 제목 + | "sample REST 애플리케이션" |
|
|
Swagger가 | false |
|
| version+ | "1.0.0" |
+ 옵션은 Swagger의 BeanConfig에 정의되어 있습니다.
++ 옵션은 Swagger의 ReaderConfig에 정의되어 있습니다.
=== Karaf 구현
이 섹션에서는 JAR 파일 내부에 정의되어 있고 Karaf 컨테이너의 Fuse에 배포되는 REST 서비스가 있는 Swagger2Feature를 사용하는 방법에 대해 설명합니다.
==== Quickstart 예
Fuse 소프트웨어 다운로드 페이지에서 Red Hat Fuse 빠른 시작 을 다운로드할 수 있습니다.
빠른 시작 zip 파일에는 CXF를 사용하여 RESTful(JAX-RS) 웹 서비스를 생성하는 방법과 Swagger를 활성화하고 JAX-RS 엔드포인트에 주석을 추가하는 방법을 설명하는 빠른 시작용 /cxf/rest/ 디렉터리가 포함되어 있습니다.
==== Swagger 활성화
Swagger를 활성화하는 데는 다음이 포함됩니다.
CXF 클래스(
org.apache.cxf.jaxrs.swagger.Swagger2Feature)를 <jaxrs:server> 정의에 추가하여 CXF 서비스를 정의하는 XML 파일을 수정합니다.예를 들어 55.4 예제 XML 파일 에서 참조하십시오.
REST 리소스 클래스에서 다음을 수행합니다.
서비스에 필요한 각 주석에 대해 Swagger API 주석을 가져옵니다.
import io.swagger.annotations.*
여기서 * =
,ApiOperationApiParam,ApiResponse,ApiResponses등.자세한 내용은
https://github.com/swagger-api/swagger-core/wiki/Annotations으로 이동합니다.예를 들어 55.5 예제 리소스 클래스 에서 참조하십시오.
-
JAX-RS 주석이 있는 끝점에 Swagger 주석을 추가합니다(
@PATH,@POST ,@GET ,@GET,@GET ,@Consumes,@DELETE,@PathParam등).
예를 들어 55.5 예제 리소스 클래스 에서 참조하십시오.
55.4 예제 XML 파일
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs"
xmlns:cxf="http://cxf.apache.org/blueprint/core"
xsi:schemaLocation="
http://www.osgi.org/xmlns/blueprint/v1.0.0
https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
http://cxf.apache.org/blueprint/jaxrs
http://cxf.apache.org/schemas/blueprint/jaxrs.xsd
http://cxf.apache.org/blueprint/core
http://cxf.apache.org/schemas/blueprint/core.xsd">
<jaxrs:server id="customerService" address="/crm">
<jaxrs:serviceBeans>
<ref component-id="customerSvc"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider"/>
</jaxrs:providers>
<jaxrs:features>
<bean class="org.apache.cxf.jaxrs.swagger.Swagger2Feature">
<property name="title" value="Fuse:CXF:Quickstarts - Customer Service" />
<property name="description" value="Sample REST-based Customer Service" />
<property name="version" value="${project.version}" />
</bean>
</jaxrs:features>
</jaxrs:server>
<cxf:bus>
<cxf:features>
<cxf:logging />
</cxf:features>
<cxf:properties>
<entry key="skip.default.json.provider.registration" value="true" />
</cxf:properties>
</cxf:bus>
<bean id="customerSvc" class="org.jboss.fuse.quickstarts.cxf.rest.CustomerService"/>
</blueprint>
55.5 예제 리소스 클래스
.
.
.
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
.
.
.
@Path("/customerservice/")
@Api(value = "/customerservice", description = "Operations about customerservice")
public class CustomerService {
private static final Logger LOG =
LoggerFactory.getLogger(CustomerService.class);
private MessageContext jaxrsContext;
private long currentId = 123;
private Map<Long, Customer> customers = new HashMap<>();
private Map<Long, Order> orders = new HashMap<>();
public CustomerService() {
init();
}
@GET
@Path("/customers/{id}/")
@Produces("application/xml")
@ApiOperation(value = "Find Customer by ID", notes = "More notes about this
method", response = Customer.class)
@ApiResponses(value = {
@ApiResponse(code = 500, message = "Invalid ID supplied"),
@ApiResponse(code = 204, message = "Customer not found")
})
public Customer getCustomer(@ApiParam(value = "ID of Customer to fetch",
required = true) @PathParam("id") String id) {
LOG.info("Invoking getCustomer, Customer id is: {}", id);
long idNumber = Long.parseLong(id);
return customers.get(idNumber);
}
@PUT
@Path("/customers/")
@Consumes({ "application/xml", "application/json" })
@ApiOperation(value = "Update an existing Customer")
@ApiResponses(value = {
@ApiResponse(code = 500, message = "Invalid ID supplied"),
@ApiResponse(code = 204, message = "Customer not found")
})
public Response updateCustomer(@ApiParam(value = "Customer object that needs
to be updated", required = true) Customer customer) {
LOG.info("Invoking updateCustomer, Customer name is: {}", customer.getName());
Customer c = customers.get(customer.getId());
Response r;
if (c != null) {
customers.put(customer.getId(), customer);
r = Response.ok().build();
} else {
r = Response.notModified().build();
}
return r;
}
@POST
@Path("/customers/")
@Consumes({ "application/xml", "application/json" })
@ApiOperation(value = "Add a new Customer")
@ApiResponses(value = { @ApiResponse(code = 500, message = "Invalid ID
supplied"), })
public Response addCustomer(@ApiParam(value = "Customer object that needs to
be updated", required = true) Customer customer) {
LOG.info("Invoking addCustomer, Customer name is: {}", customer.getName());
customer.setId(++currentId);
customers.put(customer.getId(), customer);
if (jaxrsContext.getHttpHeaders().getMediaType().getSubtype().equals("json"))
{
return Response.ok().type("application/json").entity(customer).build();
} else {
return Response.ok().type("application/xml").entity(customer).build();
}
}
@DELETE
@Path("/customers/{id}/")
@ApiOperation(value = "Delete Customer")
@ApiResponses(value = {
@ApiResponse(code = 500, message = "Invalid ID supplied"),
@ApiResponse(code = 204, message = "Customer not found")
})
public Response deleteCustomer(@ApiParam(value = "ID of Customer to delete",
required = true) @PathParam("id") String id) {
LOG.info("Invoking deleteCustomer, Customer id is: {}", id);
long idNumber = Long.parseLong(id);
Customer c = customers.get(idNumber);
Response r;
if (c != null) {
r = Response.ok().build();
customers.remove(idNumber);
} else {
r = Response.notModified().build();
}
return r;
}
.
.
.
}
=== spring 부팅 구현
이 섹션에서는 Spring Boot에서 Swagger2Feature를 사용하는 방법에 대해 설명합니다.
==== Quickstart 예
빠른 시작 예 (https://github.com/fabric8-quickstarts/spring-boot-cxf-jaxrs)는 Spring Boot와 함께 Apache CXF를 사용하는 방법을 보여줍니다. 빠른 시작에서는 Swagger가 활성화된 CXF JAX-RS 끝점을 포함하는 애플리케이션을 구성하는 Spring Boot를 사용합니다.
==== Swagger 활성화
Swagger를 활성화하는 데는 다음이 포함됩니다.
REST 애플리케이션에서 다음을 수행합니다.
Swagger2feature 가져오기:
import org.apache.cxf.jaxrs.swagger.Swagger2Feature;
CXF 엔드포인트에 Swagger2Feature 추가:
endpoint.setFeatures(Arrays.asList(new Swagger2Feature()));
예를 들어 55.1 예 REST 애플리케이션 예 에서 참조하십시오.
Java 구현 파일에서 서비스에 필요한 각 주석에 대해 Swagger API 주석을 가져옵니다.
import io.swagger.annotations.*
여기서 * =
,ApiOperationApiParam,ApiResponse,ApiResponses등.자세한 내용은
https://github.com/swagger-api/swagger-core/wiki/Annotations에서 참조하십시오.예를 들어 55.2 예 Java 구현 파일 에서 참조하십시오.
Java 파일에서 Swagger 주석을 JAX-RS 주석에 추가합니다(
@PATH,@PUT,@GET ,@GET,@509 ,@Consumes,@DELETE,@PathParam등).예를 들어 55.3 예 Java 파일 에서 참조하십시오.
55.1 예 REST 애플리케이션 예
package io.fabric8.quickstarts.cxf.jaxrs;
import java.util.Arrays;
import org.apache.cxf.Bus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.swagger.Swagger2Feature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SampleRestApplication {
@Autowired
private Bus bus;
public static void main(String[] args) {
SpringApplication.run(SampleRestApplication.class, args);
}
@Bean
public Server rsServer() {
// setup CXF-RS
JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();
endpoint.setBus(bus);
endpoint.setServiceBeans(Arrays.<Object>asList(new HelloServiceImpl()));
endpoint.setAddress("/");
endpoint.setFeatures(Arrays.asList(new Swagger2Feature()));
return endpoint.create();
}
}
55.2 예 Java 구현 파일
import io.swagger.annotations.Api;
@Api("/sayHello")
public class HelloServiceImpl implements HelloService {
public String welcome() {
return "Welcome to the CXF RS Spring Boot application, append /{name} to call the hello service";
}
public String sayHello(String a) {
return "Hello " + a + ", Welcome to CXF RS Spring Boot World!!!";
}
}
55.3 예 Java 파일
package io.fabric8.quickstarts.cxf.jaxrs;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.stereotype.Service;
@Path("/sayHello")
@Service
public interface HelloService {
@GET
@Path("")
@Produces(MediaType.TEXT_PLAIN)
String welcome();
@GET
@Path("/{a}")
@Produces(MediaType.TEXT_PLAIN)
String sayHello(@PathParam("a") String a);
}