如何使用依赖注入在Spring中注入资源类实例

Joh*_*ein 6 java spring dependency-injection spring-mvc aws-sdk

我是春天的新手。有一种情况,我编写了一个实现 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
    }
}
Run Code Online (Sandbox Code Playgroud)

我现在就是这样做的。请告诉我是否正常或资源泄漏。如果是的话我该怎么办?

med*_*088 4

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

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

  • 不,您不需要使用 new 关键字。不过,您需要为 try-with-resources 块提供一个局部变量。对于您的示例,您可以尝试 (Daws closableHaws = haws) {/**您的代码*/}。或者,如果您需要更精确地控制何时以及应该关闭什么,请使用finally 块。 (2认同)