Close

Spring - Prototype Bean Example

[Last Updated: Mar 19, 2021]

Following example shows that a new instance is used whenever a prototype bean is injected.

Example

A prototype bean

package com.logicbig.example;

public class ServiceBean {

}

Other beans injecting prototype bean

package com.logicbig.example;


import org.springframework.beans.factory.annotation.Autowired;

public class ClientBean1 {
  @Autowired
  private ServiceBean serviceBean;

  public void doSomething(){
      System.out.println("from ClientBean1: serviceBean: "+System.identityHashCode(serviceBean));
  }
}
package com.logicbig.example;


import org.springframework.beans.factory.annotation.Autowired;

public class ClientBean2 {
  @Autowired
  private ServiceBean serviceBean;

  public void doSomething(){
      System.out.println("from ClientBean2: serviceBean: "+System.identityHashCode(serviceBean));
  }
}

Defining beans and running example app

package com.logicbig.example;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

public class AppMain {
  @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  @Bean
  public ServiceBean serviceBean(){
      return new ServiceBean();
  }

  @Bean
  public ClientBean1 clientBean1(){
      return new ClientBean1();
  }

  @Bean
  public ClientBean2 clientBean2(){
      return new ClientBean2();
  }

  public static void main(String[] args) {
      AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(AppMain.class);
      context.getBean(ClientBean1.class).doSomething();
      context.getBean(ClientBean2.class).doSomething();
  }
}

Output

from ClientBean1: serviceBean: 661422630
from ClientBean2: serviceBean: 1976448008

Example Project

Dependencies and Technologies Used:

  • spring-context 4.2.3.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.6.3

Spring Prototype Bean Example Select All Download
  • spring-prototype-scope-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • AppMain.java

    See Also