gpt4 book ai didi

java - 使用Autowire获取spring xml中配置的sftpChannel

转载 作者:行者123 更新时间:2023-12-01 10:47:02 24 4
gpt4 key购买 nike

我正在使用以下 spring 配置将文件从本地文件夹传输到远程 SFTP 服务器。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:int="http://www.springframework.org/schema/integration"
xmlns:sftp="http://www.springframework.org/schema/integration/sftp"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/sftp
http://www.springframework.org/schema/integration/sftp/spring-integration-sftp-2.2.xsd">

<bean id="sftpSessionFactory"
class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
<property name="host" value="xxxxxxx" />
<property name="knownHosts" value = "C:\knownhosts"/>
<property name="user" value="wildfly" />
<property name="password" value="w!ldfly" />
<property name="port" value="22" />
</bean>

<int:channel id="sftpChannel" />

<sftp:outbound-channel-adapter id="triggerFtpOutBound" channel="sftpChannel"
session-factory="sftpSessionFactory" remote-directory="/home/wildfly">
</sftp:outbound-channel-adapter>

我正在使用以下代码发送文件。

@Autowired
private MessageChannel sftpChannel;

Function()
{
File f = new File("c:/test.txt");
Message<File> message = MessageBuilder.withPayload(f).build();
sftpChannel.send(message);
}

我在 sftpChannel.send(message) 处收到空指针异常。如何在代码中 Autowiring sftpChannel?

以下代码有效。但是,我想自动连接 sftpChannel。

ApplicationContext context = new ClassPathXmlApplicationContext("spring/config/spring-sftp.xml");
MessageChannel sftpChannel = context.getBean("sftpChannel", MessageChannel.class);

File f = new File("c:/test.txt");
Message<File> message = MessageBuilder.withPayload(f).build();
sftpChannel.send(message);

最佳答案

为了使用 Autowiring ,您需要包含

<context:annotation-config />

到您的配置文件

<beans 
//...
xmlns:context="http://www.springframework.org/schema/context"
//...
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
//...

<context:annotation-config />
//...
</beans>

这里有一个完整的例子

http://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/

关于java - 使用Autowire获取spring xml中配置的sftpChannel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34121182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com