Reputation: 2590
Suppose we have a method for creating some bean
@Bean MongoClient getMongo() {}
Occasionally, I see in examples people calling several times to the method itself when they want to use the bean (in our example getMongo()
)
Does Spring Boot somehow enable the creation of the bean only once or is it being created with every call to the method?
Upvotes: 4
Views: 4257
Reputation: 330
Actually each time you get the same object. As it was said, the default scope for spring beans is singleton which means there is only one instance of your class in Spring container.
Why do you receive the same object each time?
It's because @Configuration annotation that you used in your class implicates creation of proxy (which is subclass of your class annotated with @Configuration). This proxy stores singleton and returns reference to it whenever you call @Bean method.
Why @Bean method returns reference instead of creating object as it is in implementation?
Proxy also overrides your @Bean method.
Upvotes: 8