Create Multiple Object Spring Java Class

Create Multiple Object Spring Java Class

If you have worked with Spring framework then you are familiar with spring bean scope:

  • singleton: This is default scope of the bean if you don’t define scopes then bean will be singleton (One object)
  • prototype: In this scope multiple object will be created whenever you call the bean.
  • request: This scoped is an HTTP request which is valid in web aware spring context
  • session: This is also an HTTP session which is valid in web aware spring context
  • global-session: This scope is global HTTP session which is valid in web aware spring context

In this example I wanted to how if you define bean scope as prototype below:

<bean id="messageProcessor" class="com.javahonk.MessageProcessor" scope="prototype"/>
  • Once you define bean scope “prototype” type then every-time you call the bean new object will be crated. Tricky part is how you get multiple instance in Java:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

public class GetMultipleInstanceOfBean {
	
	@Autowired
	private ApplicationContext applicationContext;
	
	private MessageProcessor[] processors;
	
	public void getMultipleInstance(){
		
		//Let say you want to create 10 ne instance of processor keep in MessageProcessor array
		
		for (int i = 0; i < 15; i++) {
			processors[i] = applicationContext.getBean(MessageProcessor.class);
		}
	}

}
  • For more information please visit Spring official link here

Leave a Reply

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