这里,如果StudentInfo类是原型(prototype),那么它将创建两个单独的引用,这是可以的,但是在单例的情况下,它也会创建两个名为student和student1的bean,然后它打破了每个应用程序上下文的单例规则。如果我遗漏了什么,请告诉我。在这种情况下,我们如何为每个应用程序上下文创建一个单例 bean?
@Configuration
@ComponentScan("com.spring")
public class AnnotationConfiguration {
@Bean(name="student")
public StudentInfo info() {
return new StudentInfo("girraj","gupta");
}
@Bean(name="student1")
public StudentInfo info1() {
return new StudentInfo("girraj1","gupta1");
}
}
最佳答案
When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.
在您的示例中,您正在创建同一类的两个不同的 bean。由于作用域特定于 bean,因此与类本身无关。
关于java - 如果使用@Bean标签创建一个bean,那么我们可以创建两个bean。每个 applicationContext 如何是单例的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55672011/