简体   繁体   中英

How to inject resource Class instance in Spring using Dependency injection

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

My concern is if I use @Autowired and later use it in function will Spring automatically close the resource object after ending 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
    }
}

I am now doing it this way. Please tell me is it fine or the resource is leaking. If yes what can I do then?

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

If you need to create and close the object on each method invocation you should use try-with-resources

AutoCloseable will never be closed by Spring if you don't use try-with-resources or explicitly call close()

void close() throws Exception Closes this resource, relinquishing any underlying resources. This method is invoked automatically on objects managed by the try-with-resources statement.

from javadoc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM