How to add an instance of a resource class to Spring using dependency injection

I am new to Spring. There is a case for which I wrote a class that implements the AutoCloseable interface. Now I want to use it as dependency injection.

I am worried that if I use @Autowired and later use it in a function, will Spring automatically close the resource object upon completion of the scope or any exception?

@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
    }
}

      

Now I do it like this. Please tell me if this is normal or the resource is leaking. If so, what can I do?

+3


source to share


2 answers


For Spring managed beans, you can either implement the DisposableBean interface or use the @PreDestroy annotation. Spring will call destroy method when destroying the application context.



If you need to create and close an object on every method call you should use try-with-resources

+2


source


AutoCloseable will never be closed by Spring unless you use try-with-resources

or explicitly callclose()

void close () throws an exception Closes this resource, discarding any underlying resources. This method is called automatically for objects managed by a try-with-resources statement.



from javadoc

0


source







All Articles