我的班级是一名sftp投手。它实现DirectoryListener并实现fileAdded方法以监视何时将新事件添加到sftp目录。代码看起来像
@SpringBootApplication
@Slf4j
public class SftpBridge implements DirectoryListener, IoErrorListener, InitialContentListener {
@Autowired
private SftpBridgeConfig config;
@Autowired
public SftpDirectory sftpDirectory;
public static void main(final String[] args) throws Exception {
SpringApplication.run(SftpBridge.class, args);
}
@PostConstruct
public void postConstruct() {
LOG.info("Initializing...");
initialize();
LOG.info("Initialized!");
}
private void initialize() {
pollSftp();
}
public void pollSftp() {
try {
while (true) {
LOG.info("monitoring directory: " + "/");
PolledDirectory polledDirectory = sftpDirectory;
DirectoryPoller dp = DirectoryPoller.newBuilder()
.addPolledDirectory(polledDirectory)
.addListener(new SftpBridge())
// other settings
//remove this later
.enableFileAddedEventsForInitialContent() // optional (disabled by default). FileAddedEvents fired for directories initial content.
//TODO: enable later for subdirectory polling
//.enableParallelPollingOfDirectories() // optional (disabled by default).
.setDefaultFileFilter(new RegexFileFilter(".*csv")) // optional. Only consider files ending with "xml".
.setThreadName("sftp-poller") // sets the name of the the polling thread
.setPollingInterval(10, TimeUnit.SECONDS)
.start();
TimeUnit.HOURS.sleep(2);
dp.stop();
}
} catch (final Exception e) {
LOG.error("Error monitoring ftp host", e);
}
}
由于在Spring启动应用程序初始化期间由initialize()调用pollSftp(),因此可以看到@Autowired组件SftpBridgeConfig配置。
我的问题是我的类实现了DirectoryListener,我必须覆盖fileAdded事件,以便在添加新的ftp文件时采取一些操作。
@Override
public void fileAdded(FileAddedEvent event) {
LOG.info("Added: " + event.getFileElement());
//implementing DirectoryListener
//@Autowired component config is null here as it is called from a polling thread
}
在fileAdded(FileAddedEvent事件)方法中,我的@Autowired组件配置为null,因为在Spring boot init期间不调用此方法。构造代码的最佳方法是什么,以便在sftp目录轮询线程调用fileAdded()时@Autowired组件配置可用?
感谢您的任何建议。
编辑:@Andreas - 我已经填写了pollSftp()方法,该方法将该类添加为DirectoryListener。感谢
答案 0 :(得分:0)
SftpBridgeConfig中是否有注释? 比照@Service @Component
如果是配置类,需要在spring上下文中注册@Bean。 比照@Bean(name ="")或@Bean
ex)消息源配置
@Configuration
public class MessageSourceConfiguration {
@Bean
public MessageSource messageSource() {
// statements
}
}