简体   繁体   中英

Java Spring Boot FTPClient connection method from another class doesn´t work

I am trying to make a extra class that would take care of connection and status of the user, but I am still getting some wierd error, that I don´t understand.

This is my ´FTPConnection class I created private ftpClient using DI (I have @Bean annotation in main class) and I am trying to connect to the server using this method from another class

@Autowired
private FTPClient ftpClient;

public void connect() {
    try {
        ftpClient.connect("host");
        ftpClient.login("username", "password");

        int reply = ftpClient.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }

    }
    catch (IOException ex) {
        System.out.println(ex.getMessage());
    }
}

And this is the class with the RequestMapping methods

@PostMapping("/uploadFile")
    public void uploadFile(@RequestParam("file") MultipartFile file) {

        var connection = new FTPConnection();

        try {

            connection.connect();
            System.out.println(connection.isConnected());
            FTPClient ftpClient = connection.getFtpClient();

            ftpClient.changeWorkingDirectory("/usb");
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            [...]

And the error that I am getting is

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root java.lang.NullPointerException: null at com.tenpetr.FTPFileUploader.FTPConnection.connect(FTPConnection.java:16) ~[main/:na] at com.tenpetr.FTPFileUploader.FileTransfer.uploadFile(FileTransfer.java:29) ~[main/:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)...

Dou you have any idea, why I am stuck here? Thanks for your advices.

My guess is (will update after having more data) that the FtpClient is not correctly initialized and thus the FtpConnection is not correctly initialized as well.

TO BE UPDATED

Defining a bean with singleton scope means the container creates a single instance of that bean

edited:

@Bean
@Scope("singleton")
    public FTPClient  ftpClient(){
        return new FTPClient();
    }

This won't work if you're trying to autowire an interface

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM