基於註解的配置

以下範例來自範例儲存庫,展示了當您使用註解而不是 XML 時可使用的一些配置選項

@EnableIntegration (1)
@IntegrationComponentScan (2)
@Configuration
public static class Config {

    @Value(${some.port})
    private int port;

    @MessagingGateway(defaultRequestChannel="toTcp") (3)
    public interface Gateway {

        String viaTcp(String in);

    }

    @Bean
    @ServiceActivator(inputChannel="toTcp") (4)
    public MessageHandler tcpOutGate(AbstractClientConnectionFactory connectionFactory) {
        TcpOutboundGateway gate = new TcpOutboundGateway();
        gate.setConnectionFactory(connectionFactory);
        gate.setOutputChannelName("resultToString");
        return gate;
    }

    @Bean (5)
    public TcpInboundGateway tcpInGate(AbstractServerConnectionFactory connectionFactory)  {
        TcpInboundGateway inGate = new TcpInboundGateway();
        inGate.setConnectionFactory(connectionFactory);
        inGate.setRequestChannel(fromTcp());
        return inGate;
    }

    @Bean
    public MessageChannel fromTcp() {
        return new DirectChannel();
    }

    @MessageEndpoint
    public static class Echo { (6)

        @Transformer(inputChannel="fromTcp", outputChannel="toEcho")
        public String convert(byte[] bytes) {
            return new String(bytes);
        }

        @ServiceActivator(inputChannel="toEcho")
        public String upCase(String in) {
            return in.toUpperCase();
        }

        @Transformer(inputChannel="resultToString")
        public String convertResult(byte[] bytes) {
            return new String(bytes);
        }

    }

    @Bean
    public AbstractClientConnectionFactory clientCF() { (7)
        return new TcpNetClientConnectionFactory("localhost", this.port);
    }

    @Bean
    public AbstractServerConnectionFactory serverCF() { (8)
        return new TcpNetServerConnectionFactory(this.port);
    }

}
1 標準 Spring Integration 註解,啟用整合應用程式的基礎架構。
2 搜尋 @MessagingGateway 介面。
3 流程用戶端的進入點。呼叫應用程式可以針對此 Gateway Bean 使用 @Autowired 並調用其方法。
4 輸出端點由 MessageHandler 和包裝它的消費者組成。在此情境中,@ServiceActivator 根據通道類型配置端點。
5 輸入端點(在 TCP/UDP 模組中)都是訊息驅動的,因此只需要宣告為簡單的 @Bean 實例即可。
6 此類別為此範例流程提供許多 POJO 方法(伺服器端的 @Transformer@ServiceActivator 以及用戶端的 @Transformer)。
7 用戶端連線工廠。
8 伺服器端連線工廠。