我们是否可以使用@Component
Annotation创建特定类(例如Student类(的多个对象,因为只能有1个字符串传递给@Component
Annotation(@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
这样可能是实体的对象,通常不会这样做(如果在应用程序中使用数据库,则很可能反映出数据库中的内容(。