" BindException:已在使用的地址"在Spring中使用Apache FtpServer

时间:2016-03-31 21:36:32

标签: java spring spring-boot

我按如下方式配置了Apache FtpServer:

@Component
public class FtpDummyServer {

private FtpServer server;

@PostConstruct
public void init() throws FtpException {
    ..some initialization
    this.server = serverFactory.createServer();
    this.server.start();
}

@PreDestroy
public void stop() {
    this.server.stop();
}

请注意,服务器是在@PostConstruct中自动启动的。我在SpringBoot中配置了不同的测试,如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MainApplication.class)
@WebIntegrationTest
public class ApplicationTestX {
...
}

当我单独运行测试时,它们会成功。但是,当我一起运行它们时,我得到java.net.BindException: Address already in use: bind。我怎么能避免这种情况?

2 个答案:

答案 0 :(得分:3)

如果您查看异常堆栈跟踪,您将看到ftp服务器尝试使用的地址。像Smth一样

  

引起:org.apache.ftpserver.FtpServerConfigurationException:无法绑定到地址0.0.0.0/0.0.0.0:21,请检查配置

可能是因为:

  1. 您的应用的另一个实例使用地址。如果是这样,你需要终止它们。
  2. 其他一些进程使用地址/端口。在这种情况下,您可以重新配置ftp服务器以绑定到另一个地址。

    FtpServerFactory serverFactory = new FtpServerFactory();
    
    ListenerFactory factory = new ListenerFactory();
    factory.setPort(2222); //use alternative port instead of default 21
    serverFactory.addListener("default", factory.createListener());
    
    server = serverFactory.createServer();
    server.start();
    
  3. 使用netstat确定保存地址的进程ID。

答案 1 :(得分:2)

对于每个测试,都会创建一个FtpDummyServer。但是,从未调用过@PreDestroy。 @DirtiesContext解决了这个问题。