【发布时间】:2021-04-19 18:15:49
【问题描述】:
我们能否使用@Component Annotation 创建特定类的多个对象(例如Student 类),因为只有1 个String 传递给@Component Annotation (@Component("Student1"))?
【问题讨论】:
标签: java spring dependency-injection spring-annotations
我们能否使用@Component Annotation 创建特定类的多个对象(例如Student 类),因为只有1 个String 传递给@Component Annotation (@Component("Student1"))?
【问题讨论】:
标签: java spring dependency-injection spring-annotations
没有。 @Component 注释告诉 Spring 应该创建该类的单个实例。您在注解中传递的值反映了“Spring bean”的名称。
如果要创建多个实例,可以在@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 这样可能是实体的对象执行此操作(如果您在应用程序中使用数据库,则很可能反映您在数据库中拥有的内容)。
【讨论】: