Following example shows that a new instance is used whenever a prototype bean is injected.
package com.logicbig.example; public class ServiceBean { }
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)); } }
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(); } }
from ClientBean1: serviceBean: 661422630from ClientBean2: serviceBean: 1976448008
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.