【问题标题】:How to inject resource Class instance in Spring using Dependency injection如何使用依赖注入在 Spring 中注入资源类实例
【发布时间】:2015-08-05 09:36:33
【问题描述】:

我是 Spring 新手。有一种情况,我编写了一个实现 AutoCloseable 接口的类。现在我想用它作为依赖注入。

我担心如果我使用@Autowired 并且稍后在函数中使用它,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
    }
}

我现在就是这样做的。请告诉我它很好还是资源泄漏。如果是,那我该怎么办?

【问题讨论】:

    标签: java spring spring-mvc dependency-injection aws-sdk


    【解决方案1】:

    对于 Spring 托管 bean,您可以实现 DisposableBean 接口或使用 @PreDestroy 注释。 Spring会在应用上下文被销毁时调用destroy方法。

    如果您需要在每次方法调用时创建和关闭对象,您应该使用try-with-resources

    【讨论】:

    • 我是否必须使用 "new" 关键字实例化对象才能使用 try-with-resource 实现这一点?
    • 不,您不需要使用新关键字。不过,您需要为 try-with-resources 块提供一个局部变量。对于您的示例,您可以尝试 (Daws closableHaws = haws) {/**your code*/}。或者,如果您需要更精确地控制应该关闭的时间和内容,请使用 finally 块。
    • 是的,我已经做到了,它也在关闭资源。除此之外,我还可以通过 finally 以老式方式关闭它。如果我最终使用,那么我不需要将它存储在局部变量中。谢谢它的工作。
    【解决方案2】:

    如果您不使用 try-with-resources 或显式调用 close(),则 AutoCloseable 永远不会被 Spring 关闭

    无效关闭() 抛出异常 关闭此资源,放弃任何基础资源。在 try-with-resources 语句管理的对象上自动调用此方法。

    来自javadoc

    【讨论】:

      猜你喜欢
      • 2011-05-27
      • 2011-12-05
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 2010-10-15
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多