如何在 Spring 集成中使用 JAVA DSL 基于模式进行通道拦截?

How to do channel interceptor based on pattern using JAVA DSL in Spring Integration?

我们正计划将我们的代码从 Spring 集成 XML 迁移到 DSL。在 XML 版本中,我们使用通道名称模式进行跟踪。

例如:如果频道名称有 *_EL_*,我们拦截该频道并进行一些日志记录。

如何在 Java dsl 中做这种或更简单。

@GlobalChannelInterceptor适合你。它是 Spring Integration Core 的一部分。

所以,你必须这样做:

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

@Bean
@GlobalChannelInterceptor(patterns = "*_EL_*")
public WireTap baz() {
    return new WireTap(this.bar());
}

我的意思是指定 ChannelInterceptor @Bean 并用该注释标记它以进行基于模式的拦截。

更新

示例测试用例演示了 @GlobalChannelInterceptor 对来自 DSL 流的 auto-created 通道的工作:

@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext
public class SO31573744Tests {

    @Autowired
    private TestGateway testGateway;

    @Autowired
    private PollableChannel intercepted;

    @Test
    public void testIt() {
        this.testGateway.testIt("foo");
        Message<?> receive = this.intercepted.receive(1000);
        assertNotNull(receive);
        assertEquals("foo", receive.getPayload());
    }


    @MessagingGateway
    public interface TestGateway {

        @Gateway(requestChannel = "testChannel")
        void testIt(String payload);

    }

    @Configuration
    @EnableIntegration
    @IntegrationComponentScan
    public static class ContextConfiguration {

        @Bean
        public IntegrationFlow testFlow() {
            return IntegrationFlows.from("testChannel")
                    .channel("nullChannel")
                    .get();
        }

        @Bean
        public PollableChannel intercepted() {
            return new QueueChannel();
        }

        @Bean
        @GlobalChannelInterceptor(patterns = "*Ch*")
        public WireTap wireTap() {
            return new WireTap(intercepted());
        }

    }

}