在Spring中使用@Component注释创建特定类的多个对象



我们是否可以使用@ComponentAnnotation创建特定类(例如Student类(的多个对象,因为只能有1个字符串传递给@ComponentAnnotation(@Component("Student1")(?

否。@Component注释告诉Spring应该创建该类的单个实例。在注释中传递的值反映了";春豆"。

如果要创建多个实例,可以在@Configuration类中使用@Bean注释:

@Configuration
public class MyConfiguration {
@Bean
public Student student1() {
return new Student();
}
@Bean
public Student student2() {
return new Student();
}
}

这段代码将在Spring上下文中创建2个Spring bean。一个具有student1名称,另一个具有student2名称。

请注意,对于像Student这样可能是实体的对象,通常不会这样做(如果在应用程序中使用数据库,则很可能反映出数据库中的内容(。

最新更新