Search code examples
javaspringdependency-injectionspring-annotations

Create multiple objects of a particular class using @Component annotation in Spring


Can we create multiple objects of a particular class (for instance class Student) using @Component Annotation, since there can be only 1 String passed to @Component Annotation (@Component("Student1"))?


Solution

  • No. The @Component annotation tells Spring that a single instance of the class should be created. The value you pass in the annotation reflects the name of the "Spring bean".

    If you want to create multiple instances, you can use the @Bean annotation in a @Configuration class:

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

    This code would create 2 Spring beans in the Spring context. One with the student1 name and the other with the student2 name.

    Note that you usually would not do this for objects like Student which are probably entities (most likely reflecting what you have in your database if you use a database in your application).