如何使用依赖注入在Spring中注入资源类实例 [英] How to inject resource Class instance in Spring using Dependency injection

查看:94
本文介绍了如何使用依赖注入在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中注入资源类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆