Singleton and Prototype Bean Scopes Examples

A simple example to demonstrates the difference between singleton scope and prototype scope with an example.In this example, I have used a Java-based configuration using @Configuration, @Bean, and @Scope annotations.Here’s an example to show you what’s the difference between bean scopes Singleton and Prototype. Let's create UserService class which is common for Singleton and Prototype scope examples.

Since the bean ‘userService’ is in singleton scope, the second retrieval by ‘userService1’ will display the message set by ‘userService’ also, even it’s retrieve by a new getBean() method. In singleton, only a single instance per Spring IoC container, no matter how many time you retrieve it with getBean(), it will always return the same instance.

Conclusion

In this example, we demonstrated the difference between singleton scope and prototype scope. Also in this example, we have used a Java-based configuration using @Configuration, @Bean, and @Scope annotations.The implementation of this simple Spring Java-based-configuration example can be found in the GitHub project – this is an Eclipse based project, so it should be easy to import and run as it is.Github Repository: Singleton and Prototype Bean Scopes Examples