Tuesday, December 20, 2011

Understanding scoped-proxy in spring framework

Let say there are two classes, namely SingletonBean and PrototypeBean class, where prototype bean reference is kept inside the singleton bean. And as the name suggests, SingletonBean is specified with "singleton" scope and "prototype" scope for PrototypeBean. Now if we access the singleton bean using the application context, it will create single instance all times. However if we access the prototype bean reference using the singleton bean reference it will also show single instance all times because it has been wrapped inside the singleton bean, which is an expected behaviour under singleton pattern scenario. But we specified the prototype scope in PrototypeBean and if we wanted to return a new PrototypeBean object every time when we access using the singleton reference(getPrototypeBean()) then we need to specify the prototype bean additionally using

or @Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS) as annotation.

Following example -

@Component

@Scope(value="singleton")

public class SingletonBean {


@Autowired

private PrototypeBean prototypeBean;
/**

*

*/

public SingletonBean() {



}

public PrototypeBean getPrototypeBean()
{

return prototypeBean;

}

public void
setPrototypeBean(PrototypeBean prototypeBean) {


this.prototypeBean = prototypeBean;
}

}


@Component

@Scope(value="prototype",
proxyMode=ScopedProxyMode.TARGET_CLASS)


public class PrototypeBean {


/**

*

*/

public PrototypeBean() {



}


}


When we test these beans after wiring them in xml file (using component-scan), we
find below results -

SingletonBean singletonBean = (SingletonBean)container.getBean("singletonBean");
System.out.println("singleton instance :"+singletonBean); //container.bean.SingletonBean@2200d5
System.out.println("prototype instance :"+singletonBean.getPrototypeBean()); //container.bean.PrototypeBean@df1832

singletonBean = (SingletonBean)container.getBean("singletonBean");
System.out.println("singleton instance :"+singletonBean); //container.bean.SingletonBean@2200d5
System.out.println("prototype instance :"+singletonBean.getPrototypeBean());//container.bean.PrototypeBean@ad8659

3 comments:

  1. This does not work, create instance variable of type int in prototype bean, when you get prototype bean for the first time, set value 10 to it.

    When you get prototype bean for the second time, get that instance variable from it, you will see what you set in first prototype object.

    ReplyDelete
  2. very good ,, why official website not describe simple type.

    ReplyDelete