How to inject resource Class instance in Spring using Dependency injection(如何使用依赖注入在Spring中注入资源类实例)
本文介绍了如何使用依赖注入在Spring中注入资源类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新来Spring的。在这种情况下,我编写了一个实现AutoCloseable接口的类。现在我想将其用作依赖项注入。
我担心的是,如果我使用@Autwire,然后在函数中使用它,Spring是否会在结束作用域或任何异常后自动关闭资源对象?
@RestController
@RequestMapping("/rest/profile")
public class ProfileController {
private Daws haws;
@Autowired
public ProfileController(Daws haws) {
this.haws = haws;
}
@RequestMapping(value = "/images/{userId}/{fileName:.+}", method = RequestMethod.GET)
public void image(@PathVariable Integer userId, @PathVariable String publicUrl, @PathVariable String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
try{
S3Object image = haws.getProfileImage(userId, fileName, request);
response.setContentType(image.getObjectMetadata().getContentType());
response.setHeader("ETag",image.getObjectMetadata().getETag());
response.setHeader("Cache-Control",image.getObjectMetadata().getCacheControl());
response.setHeader("Last-Modified",image.getObjectMetadata().getLastModified().toString());
IOUtils.copy(image.getObjectContent(), response.getOutputStream());
}catch (Exception e) {
if(e instanceof AmazonS3Exception){
//....
//....
response.setStatus(statusCode);
}
}
}
//Daws class
public class Daws implements AutoCloseable{
public S3Object getProfileImage(int userId, String fileName, HttpServletRequest request) throws IOException, ParseException, AmazonS3Exception{
S3Object image = ....;
return image;
}
@Override
public void close() throws Exception {
// TODO Auto-generated method stub
}
}
我现在就是这样做的。请告诉我是好还是资源在漏水。如果是,那么我能做些什么?
推荐答案
对于Spring托管bean,您可以实现DisposableBean接口或使用@PreDestroy注释。当应用程序上下文被销毁时,Spring将调用销毁方法。
如果需要在每次方法调用时创建和关闭对象,则应使用try-with-resources
这篇关于如何使用依赖注入在Spring中注入资源类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何使用依赖注入在Spring中注入资源类实例


基础教程推荐
猜你喜欢
- 多个组件的复杂布局 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01