Bean lifecycle and scopes · Topic 3 of 5
Singleton vs prototype
Definition​
A singleton bean (the default) is created once and shared by everyone, so it must not hold per-request state. A prototype bean is created fresh every time it is requested.
Example code​
The same instance, or a new one each time
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
class Counter { }
@Configuration
class AppConfig {
@Bean
Counter shared() { return new Counter(); } // singleton by default
@Bean
@Scope("prototype")
Counter fresh() { return new Counter(); } // a new object on every request
}
class Demo {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
System.out.println("singleton same? " + (context.getBean("shared") == context.getBean("shared")));
System.out.println("prototype same? " + (context.getBean("fresh") == context.getBean("fresh")));
}
}
}
// Output:
// singleton same? true
// prototype same? false
Finished this page? Track your progress (saved only in your browser).