Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot: Calling a @Bean method several times

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?

like image 918
yaseco Avatar asked Oct 21 '25 04:10

yaseco


1 Answers

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.

like image 172
Aleksander Nuszel Avatar answered Oct 22 '25 19:10

Aleksander Nuszel