简体   繁体   English

Spring 启动:多次调用@Bean 方法

[英]Spring Boot: Calling a @Bean method several times

Suppose we have a method for creating some bean假设我们有一个创建某个 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() )有时,我在示例中看到人们在想要使用 bean 时多次调用方法本身(在我们的示例中getMongo()

Does Spring Boot somehow enable the creation of the bean only once or is it being created with every call to the method? Spring Boot 是否以某种方式仅启用一次 bean 的创建,还是每次调用该方法时都会创建它?

Actually each time you get the same object.实际上每次你得到相同的 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. 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?为什么每次收到相同的 object?

It's because @Configuration annotation that you used in your class implicates creation of proxy (which is subclass of your class annotated with @Configuration).这是因为您在 class 中使用的 @Configuration 注释暗示了代理的创建(这是您的 class 的子类,用 @Configuration 注释)。 This proxy stores singleton and returns reference to it whenever you call @Bean method.此代理存储 singleton 并在您调用 @Bean 方法时返回对它的引用。

Why @Bean method returns reference instead of creating object as it is in implementation?为什么@Bean 方法返回引用而不是在实现中创建 object?

Proxy also overrides your @Bean method.代理还覆盖您的 @Bean 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM