Following example shows that singleton bean is created only once per Spring container.
Example
A singleton bean
package com.logicbig.example;
public class ServiceBean {
}
Other beans injecting singleton 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_SINGLETON)
@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) {
runApp();
runApp();
}
private static void runApp() {
System.out.println("--- running app ---");
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppMain.class);
context.getBean(ClientBean1.class).doSomething();
context.getBean(ClientBean2.class).doSomething();
}
}
Output--- running app --- from ClientBean1: serviceBean: 2132083608 from ClientBean2: serviceBean: 2132083608 --- running app --- from ClientBean1: serviceBean: 1423108099 from ClientBean2: serviceBean: 1423108099
We created the spring context twice to show that Spring singleton beans have different instance in different spring context (container), so they are not JVM level singletons.
Example ProjectDependencies and Technologies Used: - spring-context 4.2.3.RELEASE: Spring Context.
- JDK 1.8
- Maven 3.6.3
|