Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring,如何注入可自动关闭的资源_Java_Spring_Dependency Injection_Java 7_Try With Resources - Fatal编程技术网

Java Spring,如何注入可自动关闭的资源

Java Spring,如何注入可自动关闭的资源,java,spring,dependency-injection,java-7,try-with-resources,Java,Spring,Dependency Injection,Java 7,Try With Resources,所以我的问题是如何注入一个自动关闭的资源,理想情况下应该与Java7的try-with-resource特性一起使用。下面使用lombok的代码正确吗 AppConfig.java @Configuration public class AppConfig{ @Bean public AutoCloseable myFtpClient(){ return new MyFtpClient(); // My custom FTP Client. } }

所以我的问题是如何注入一个自动关闭的资源,理想情况下应该与Java7的try-with-resource特性一起使用。下面使用lombok的代码正确吗

AppConfig.java

@Configuration
public class AppConfig{
     @Bean
     public AutoCloseable myFtpClient(){
       return new MyFtpClient(); // My custom FTP Client.
     }
}
Sample.java
如下:-

@Slf4j
@RequiredArgsConstructor
class Sample {

    @NonNull
    private final AutoCloseable autoCloseable;

    public void execute() {
        try (final AutoCloseable ac = autoCloseable) {
            ac.connect() // do the real stuff 
        } catch (Exception e) {
            log.error("{}", e.getMessage());
        }
    }
}
此外,如果我不能注入autocloseable对象,我如何对上述类进行单元测试