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: 747161976 from ClientBean2: serviceBean: 747161976 --- running app --- from ClientBean1: serviceBean: 1696188347 from ClientBean2: serviceBean: 1696188347
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 6.1.2 (Spring Context)
Version Compatibility: 3.2.3.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|