Spring BeanFactory Singleton Prototype Objects

Spring BeanFactory Singleton Prototype Objects

BeanFactory Singleton Prototype Examples Screenshots Simple terms given

In singleton bean, only one object is created irrespective of any number of objects client creates. In prototype bean, multiple objects are created. These are illustrated in this application. Two client programs are written with the same output but using BeanFactory and applicationContext.

Note: Both BeanFactory and ApplicationContext are containers. For their difference, refer containers in Introduction to Java Spring Framework.

BeanFactory Singleton Prototype

1. Bean Program: A.java

2. Dependency XML file: applicationContext.xml

Observe the scope attribute. Singleton means only one object is created irrespective of any number calls, the client makes. But it prototype, for each object called by client, different bean objects are created.

<property name="a" value="Trainer"/>

name="a" calls setA() method.


A bean starts its life-cycle events with init() method. Spring framework provides facility to initialize the Beans using the user defined methods in place of actual life cycle methods. The user defined method is written in init-method attribute. In the above code, the init() method invokes the user defined start().

After constructors, the program execution starts with start() method.

3. First Client Program: Client1.java (Using BeanFactory)

Generally, the applicationContext.xml file is placed in src folder of MyEclipse. Infact, it can be any folder on the file system. In the above client program, the XML file is placed in C:\snr folder.

Console screenshot when Client1 is run (of BeanFactory Singleton Prototype):

BeanFactory Singleton Prototype

As a1 object is singleton, both times the same object is returned (it printed A@1aaf0b3).

As a2 object is prototype (means not singleton), two times two different objects are returned (it printed A@125fefa and A@186df0f)

4. Second Client Program: Client2.java (Using ApplicationContext)

Console screenshot when Client2 is run (of BeanFactory Singleton Prototype):

BeanFactory Singleton Prototype

The output of both the programs is same but they differ in the number of objects created in the program. Sometime, singleton may be advantageous for performance.

Pass your comments for the improvement of this tutorial "Spring BeanFactory Singleton Prototype Objects".

Leave a Reply

Your email address will not be published. Required fields are marked *