본문 바로가기
Spring Integration for Beginners

주요 Spring Integration 어노테이션

by Andrew's Akashic Records 2025. 1. 15.
728x90
4. 부록
4.1 주요 Spring Integration 어노테이션

Spring Integration for Backend Developers

주요 Spring Integration 어노테이션

Spring Integration에서 어노테이션은 통합 플로우의 설정을 간소화하고 코드 가독성을 높이는 데 중요한 역할을 합니다. 주요 어노테이션과 그 사용법을 정리합니다.

1. @MessagingGateway

  • 역할: 외부 애플리케이션과 Spring Integration 간의 진입점(Gateway) 역할을 정의합니다.
  • 사용 위치: 인터페이스에 적용.
  • 주요 속성:
    • name: Gateway 이름.
    • defaultRequestChannel: 메시지를 전달할 기본 채널.
    • defaultReplyChannel: 응답 메시지를 받을 채널.
    • errorChannel: 에러 메시지를 처리할 채널.

예제

@MessagingGateway(name = "orderGateway", defaultRequestChannel = "orderInputChannel")
public interface OrderGateway {
    @Gateway(requestChannel = "orderInputChannel")
    void placeOrder(String orderJson);
}

 

사용법 확장

  • 동적 채널 지정:
    • 특정 상황에 따라 동적으로 채널을 지정할 수 있습니다.
@MessagingGateway
public interface DynamicGateway {
    @Gateway(requestChannel = "#{'${dynamic.channel.name}'}")
    void sendToDynamicChannel(String payload);
}

 

속성 요약

  • defaultHeaders:
    • 메시지에 기본 헤더를 추가합니다.
  • errorChannel:
    • 에러 처리에 사용할 채널 지정.

활용 예제

  • 동적 채널 및 에러 처리:
@MessagingGateway(defaultRequestChannel = "defaultChannel", errorChannel = "gatewayErrorChannel")
public interface AdvancedGateway {
    @Gateway(requestChannel = "#{@customChannelResolver.resolve('customChannel')}")
    void sendMessage(String payload);
}

2. @ServiceActivator

  • 역할: 메시지를 처리하는 서비스 활성화기(Service Activator)를 정의합니다.
  • 사용 위치: 메서드에 적용.
  • 주요 속성:
    • inputChannel: 입력 메시지를 받을 채널.
    • outputChannel: 처리 후 메시지를 보낼 채널.

예제

@ServiceActivator(inputChannel = "orderInputChannel", outputChannel = "processedOrderChannel")
public String processOrder(String orderJson) {
    // 메시지 처리 로직
    return "Processed: " + orderJson;
}

 

 

비동기 처리

  • @ServiceActivator에서 비동기 처리를 위해 Executor를 활용할 수 있습니다.
@Bean
@ServiceActivator(inputChannel = "asyncInputChannel", outputChannel = "asyncOutputChannel")
public MessageHandler asyncServiceActivator(Executor executor) {
    return new MethodInvokingMessageHandler(new AsyncService(), "process", executor);
}

 

속성 요약

  • requiresReply:
    • true로 설정 시, 반드시 응답 메시지를 반환해야 합니다.
  • sendTimeout:
    • 메시지를 보낼 때 타임아웃 설정(기본값: -1).

활용 예제

  • 비동기 메시지 처리:
@ServiceActivator(inputChannel = "processChannel", requiresReply = true)
public String processMessage(String payload) {
    return "Processed: " + payload;
}

 

3. @Transformer

  • 역할: 메시지를 변환하는 Transformer를 정의합니다.
  • 사용 위치: 메서드에 적용.
  • 주요 속성:
    • inputChannel: 입력 메시지를 받을 채널.
    • outputChannel: 변환된 메시지를 보낼 채널.

예제

@Transformer(inputChannel = "rawOrderChannel", outputChannel = "formattedOrderChannel")
public String transformOrder(String rawOrder) {
    // 메시지 변환 로직
    return rawOrder.toUpperCase();
}

 

4. @Filter

  • 역할: 조건에 따라 메시지를 필터링합니다.
  • 사용 위치: 메서드에 적용.
  • 주요 속성:
    • inputChannel: 입력 메시지를 받을 채널.
    • outputChannel: 필터링된 메시지를 보낼 채널.
    • discardChannel: 필터링되지 않은 메시지를 보낼 채널.

예제

@Filter(inputChannel = "orderInputChannel", outputChannel = "validOrderChannel", discardChannel = "invalidOrderChannel")
public boolean filterOrder(String orderJson) {
    return orderJson.contains("valid");
}

 

조건부 메시지 처리

  • 메시지를 필터링하면서 추가 로직을 실행할 수 있습니다.
@Filter(inputChannel = "rawDataChannel", outputChannel = "processedDataChannel")
public boolean filterMessage(String payload) {
    if (payload.startsWith("valid")) {
        System.out.println("Valid message: " + payload);
        return true;
    }
    return false;
}

 

속성 요약

  • discardChannel:
    • 필터링된 메시지를 보낼 채널.
  • throwExceptionOnRejection:
    • true로 설정 시, 필터링된 메시지에 대해 예외 발생.

5. @Splitter

  • 역할: 하나의 메시지를 여러 메시지로 분리합니다.
  • 사용 위치: 메서드에 적용.
  • 주요 속성:
    • inputChannel: 입력 메시지를 받을 채널.
    • outputChannel: 분리된 메시지를 보낼 채널.

예제

@Splitter(inputChannel = "bulkOrderChannel", outputChannel = "individualOrderChannel")
public List<String> splitOrders(String bulkOrders) {
    return Arrays.asList(bulkOrders.split(","));
}

 

속성 요약

  • applySequence:
    • true로 설정 시, 메시지 그룹과 시퀀스 정보를 유지.
  • adviceChain:
    • Splitter 동작 전후에 추가 로직 실행.

활용 예제

  • 파일 처리 예제:
@Splitter(inputChannel = "fileChannel")
public List<String> splitFile(String fileContent) {
    return Arrays.asList(fileContent.split("\n"));
}
  • 메시지 시퀀스 유지:
@Splitter(inputChannel = "batchChannel", applySequence = true)
public List<String> splitBatch(String batch) {
    return List.of(batch.split(","));
}

6. @Router

  • 역할: 메시지를 조건에 따라 다른 채널로 라우팅합니다.
  • 사용 위치: 메서드에 적용.
  • 주요 속성:
    • inputChannel: 입력 메시지를 받을 채널.
    • defaultOutputChannel: 기본 출력 채널.

예제

@Router(inputChannel = "orderInputChannel", defaultOutputChannel = "defaultChannel")
public String routeOrder(String orderJson) {
    if (orderJson.contains("priority")) {
        return "priorityOrderChannel";
    }
    return "regularOrderChannel";
}

 

다중 채널 라우팅

  • 조건에 따라 메시지를 여러 채널로 분배할 수 있습니다.
@Router(inputChannel = "inputChannel")
public Collection<String> routeMessage(String payload) {
    List<String> channels = new ArrayList<>();
    if (payload.contains("urgent")) channels.add("urgentChannel");
    if (payload.contains("regular")) channels.add("regularChannel");
    return channels;
}

 

속성 요약

  • applySequence:
    • true로 설정 시, 메시지 시퀀스를 유지하여 라우팅.
  • defaultOutputChannel:
    • 조건에 맞지 않는 메시지가 라우팅될 기본 채널.

활용 예제

  • 기본 채널 포함 다중 라우팅:
@Router(inputChannel = "orderChannel", defaultOutputChannel = "errorChannel")
public String routeOrder(String orderJson) {
    if (orderJson.contains("priority")) return "priorityOrderChannel";
    if (orderJson.contains("normal")) return "normalOrderChannel";
    return null;
}
728x90

7. @Poller

  • 역할: 채널의 메시지를 주기적으로 폴링(polling)하도록 설정합니다.
  • 사용 위치: @ServiceActivator, @InboundChannelAdapter 등에서 사용.
  • 주요 속성:
    • fixedRate: 폴링 주기를 밀리초 단위로 설정.
    • cron: 폴링 주기를 크론 표현식으로 설정.

예제

@InboundChannelAdapter(channel = "fileChannel", poller = @Poller(fixedRate = "5000"))
public MessageSource<File> fileReadingMessageSource() {
    return new FileReadingMessageSource();
}

속성 요약

  • fixedDelay:
    • 이전 실행이 완료된 후 대기 시간 설정.
  • maxMessagesPerPoll:
    • 한 번의 폴링에서 처리할 최대 메시지 수.

활용 예제

  • 동적 폴링 주기:
@InboundChannelAdapter(channel = "pollingChannel", poller = @Poller(fixedDelay = "#{@dynamicPollerDelay}"))
public MessageSource<String> dynamicPoller() {
    return () -> new GenericMessage<>("Polled data");
}
  • 메시지 제한:
@InboundChannelAdapter(channel = "limitedChannel", poller = @Poller(maxMessagesPerPoll = 5, fixedRate = "3000"))
public MessageSource<String> limitedPolling() {
    return () -> new GenericMessage<>("Limited data");
}

8. @InboundChannelAdapter

  • 역할: 외부 소스에서 데이터를 읽어와 채널에 전달합니다.
  • 사용 위치: 메서드에 적용.
  • 주요 속성:
    • channel: 데이터를 전달할 채널.
    • poller: 데이터를 주기적으로 가져올 폴링 설정.

예제

@InboundChannelAdapter(channel = "fileInputChannel", poller = @Poller(fixedDelay = "5000"))
public MessageSource<File> fileSource() {
    FileReadingMessageSource source = new FileReadingMessageSource();
    source.setDirectory(new File("/input"));
    return source;
}

9. @BridgeTo

  • 역할: 하나의 채널을 다른 채널로 연결합니다.
  • 사용 위치: 메서드에 적용.
  • 주요 속성:
    • inputChannel: 입력 메시지를 받을 채널.
    • outputChannel: 메시지를 보낼 채널.

예제

@BridgeTo(inputChannel = "inputChannel", outputChannel = "outputChannel")
public void bridge() {
}

10. @Handler

  • 역할: 메시지를 처리하는 핸들러 정의.
  • 사용 위치: 메서드에 적용.
  • 주요 속성:
    • inputChannel: 입력 메시지를 받을 채널.
    • outputChannel: 처리된 메시지를 보낼 채널.

예제

@Handler(inputChannel = "processChannel", outputChannel = "resultChannel")
public String handle(String payload) {
    return "Handled: " + payload;
}

11. @IntegrationComponentScan

역할

  • Spring Integration 컴포넌트를 스캔하여 자동으로 등록.
  • 기본적으로 @MessagingGateway를 포함한 컴포넌트를 탐지.
  • 프로젝트 내에서 한 번만 선언하는 것을 권장

사용 예제

@Configuration
@IntegrationComponentScan(basePackages = "com.example.integration")
public class AppConfig {
    // 추가적인 Spring Integration 설정
}

요약

어노테이션 역할 사용 위치
@MessagingGateway 외부와의 통합 진입점 설정 인터페이스
@ServiceActivator 메시지 처리 및 서비스 활성화기 정의 메서드
@Transformer 메시지 변환 로직 정의 메서드
@Filter 메시지 필터링 조건 설정 메서드
@Splitter 메시지 분리 로직 정의 메서드
@Router 메시지 라우팅 조건 설정 메서드
@Poller 폴링 주기 설정 메서드 또는 어댑터
@InboundChannelAdapter 외부 데이터 소스와 채널 연결 메서드
@BridgeTo 채널 간 연결 설정 메서드
@Handler 메시지 핸들러 정의 메서드
@IntegrationComponentScan 컴포넌트 스캔 자동 등록 클래스

 

Spring Integration의 주요 어노테이션은 통합 플로우를 간결하게 정의할 수 있도록 도와줍니다. 이들 어노테이션을 적절히 활용하면 복잡한 통합 시나리오도 효율적으로 구현할 수 있습니다.

728x90