上下文持有者建议

从版本 6.1 开始,ContextHolderRequestHandlerAdvice已引入。 此建议从请求消息中获取一些值,并将其存储在上下文持有者中。 在目标上完成执行时,该值从上下文中是明确的MessageHandler. 考虑这个建议的最佳方式类似于编程流程,我们将一些值存储到ThreadLocal,从 Target 调用中访问它,然后清理ThreadLocal执行后。 这ContextHolderRequestHandlerAdvice需要这些构造函数参数:一个Function<Message<?>, Object>作为价值提供者,Consumer<Object>作为上下文集回调,将Runnable作为上下文清理钩子。spring-doc.cadn.net.cn

以下是ContextHolderRequestHandlerAdvice可与o.s.i.file.remote.session.DelegatingSessionFactory:spring-doc.cadn.net.cn

@Bean
DelegatingSessionFactory<?> dsf(SessionFactory<?> one, SessionFactory<?> two) {
    return new DelegatingSessionFactory<>(Map.of("one", one, "two", two), null);
}

@Bean
ContextHolderRequestHandlerAdvice contextHolderRequestHandlerAdvice(DelegatingSessionFactory<String> dsf) {
    return new ContextHolderRequestHandlerAdvice(message -> message.getHeaders().get("FACTORY_KEY"),
                                      dsf::setThreadKey, dsf::clearThreadKey);
}

@ServiceActivator(inputChannel = "in", adviceChain = "contextHolderRequestHandlerAdvice")
FtpOutboundGateway ftpOutboundGateway(DelegatingSessionFactory<?> sessionFactory) {
	return new FtpOutboundGateway(sessionFactory, "ls", "payload");
}

只需向inchannel 中带有FACTORY_KEYheader 设置为onetwo. 这ContextHolderRequestHandlerAdvice将该标头中的值设置为DelegatingSessionFactory通过其setThreadKey. 然后当FtpOutboundGateway执行ls命令适当的委托SessionFactoryDelegatingSessionFactory根据其ThreadLocal. 当从FtpOutboundGateway一个ThreadLocal值在DelegatingSessionFactory根据clearThreadKey()调用ContextHolderRequestHandlerAdvice. 有关更多信息,请参阅委派 Session Factoryspring-doc.cadn.net.cn