How to inject resource Class instance in Spring using Dependency injection(如何使用依赖注入在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中注入资源类实例
 
				
         
 
            
        - 未找到/usr/local/lib 中的库 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 转换 ldap 日期 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
 
						 
						 
						 
						 
						 
				 
				 
				 
				