Spring Integration SFTP多文件夹跟踪下载遇remoteDirectoryExpression非空异常
问题
基于Spring Boot 3.2.0、Spring Integration 6.2.0技术栈开发应用,需实现跟踪SFTP多个文件夹并下载文件。按照官方指引,移除了Sftp入站适配器的remoteDirectory配置,给轮询器添加RotatingServerAdvice,相关配置代码如下:
@Bean fun advice(): RotatingServerAdvice { val keyDirectories = listOf( RotationPolicy.KeyDirectory( "foo", sftpProperties.remoteDirectory ), RotationPolicy.KeyDirectory( "foo", sftpProperties.remoteFooDirectory ) ) return RotatingServerAdvice(DelegatingSessionFactory { sftpSessionFactory() }, keyDirectories, true) } @Bean fun sftpInboundFlow(): IntegrationFlow { return IntegrationFlow .from( Sftp.inboundAdapter(sftpSessionFactory()) .preserveTimestamp(true) .deleteRemoteFiles(true) // 传输完成后删除远程文件 // 通过advice切换多个文件夹,因此注释了该行 //.remoteDirectory(sftpProperties.remoteDirectory) .regexFilter(".*\\.csv$") // 本地配置 .localFilenameExpression("#this.toUpperCase() + '.csv'") .autoCreateLocalDirectory(true) .localDirectory(File("./sftp-inbound")) ) { e: SourcePollingChannelAdapterSpec -> e.id("sftpInboundAdapter") .autoStartup(true) .poller(Pollers.fixedDelay(5000).advice(advice())) }
运行测试时抛出如下异常:
'remoteDirectoryExpression' must not be null at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:608) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:523) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:946)
解决方案
1. 解决初始化校验问题
Sftp入站适配器初始化时必须指定remoteDirectory或remoteDirectoryExpression,即使后续会通过RotatingServerAdvice切换目录,也需要设置一个默认值通过校验。
可选两种方式:
- 设置临时默认目录(比如
/dummy),轮询时RotatingServerAdvice会覆盖该值:
Sftp.inboundAdapter(sftpSessionFactory()) // ...其他配置 .remoteDirectory("/dummy") // 添加默认目录 // ...其他配置
- 通过配置项设置默认目录表达式:
Sftp.inboundAdapter(sftpSessionFactory()) // ...其他配置 .remoteDirectoryExpression("\${sftp.remote-directory}") // 用配置的主目录作为默认 // ...其他配置
2. 修正RotatingServerAdvice的Key配置
当前keyDirectories中两个目录使用了同一个key("foo"),会导致轮换逻辑混乱,应为每个目录分配唯一的key:
val keyDirectories = listOf( RotationPolicy.KeyDirectory("main", sftpProperties.remoteDirectory), RotationPolicy.KeyDirectory("foo", sftpProperties.remoteFooDirectory) )
内容的提问来源于stack exchange,提问作者Hantsy
相关产品推荐
相关产品推荐

