Results 1 to 2 of 2

Thread: Query on Prototype Scoped Beans

  1. #1
    Join Date
    Apr 2011
    Posts
    17

    Default Query on Prototype Scoped Beans

    In spring,when bean is defined with prototype scope, getBean() method will return new instance every time we call it.
    Would like to know any business scenario where we use this Prototype scope beans?
    OR
    When we have to declare the scope as prototype for bean?

  2. #2
    Join Date
    Sep 2012
    Location
    Czech Republic
    Posts
    39

    Default

    Prototypes are used where there is a state mantained for each instance (you can use singleton when there is no inner bean state that should differs among instances).
    Let's say you want to have an image thumbnailer and you want to create thumbnails of the image in different sizes. But loading an image to a memory can be costly. So you can store a loaded image in a prototype instance.

    Code:
    class ThumbnailerImpl implements Thumbnailer, ResouceHolder {
      void setResource(Resource r) {load image here from the resource}
      Resource doThumbnail(int size) {create thumbnail here}
    }
    
    class ThumbnailerFactory() {
      Thumbnailer createThumbnailer(Resource image) {
        ResourceHolder thumbnailer = ctx.getBean("thumbnailerPrototypeBean");
        thumbnailer.setResource(image);
        return (Thumbnailer) thumbnailer;
      }
    }
    Why do you want the ThumbnailerImpl class be a Spring prototype bean instead of creating its instances using new operator in the ThumbnailFactory? Maybe because you want to inject actual thumbnail algorithm into it or apply Spring AOP on it.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •