Announcement Announcement Module
Collapse
No announcement yet.
Query on Prototype Scoped Beans Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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
    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.

    Comment

    Working...
    X