【问题标题】:Create multiple objects of a particular class using @Component annotation in Spring在 Spring 中使用 @Component 注解创建特定类的多个对象
【发布时间】:2021-04-19 18:15:49
【问题描述】:

我们能否使用@Component Annotation 创建特定类的多个对象(例如Student 类),因为只有1 个String 传递给@Component Annotation (@Component("Student1"))?

【问题讨论】:

    标签: java spring dependency-injection spring-annotations


    【解决方案1】:

    没有。 @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 这样可能是实体的对象执行此操作(如果您在应用程序中使用数据库,则很可能反映您在数据库中拥有的内容)。

    【讨论】:

    • 非常感谢,这确实消除了我的疑问!
    • '@Component 注释告诉 Spring 应该创建该类的单个实例' - 假设单例范围
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2015-01-24
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    相关资源
    最近更新 更多