Java Spring,如何注入可自动关闭的资源
所以我的问题是如何注入一个自动关闭的资源,理想情况下应该与Java7的try-with-resource特性一起使用。下面使用lombok的代码正确吗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. } }
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对象,我如何对上述类进行单元测试