Search code examples
javaspringdependency-injectionejbinversion-of-control

How to inject 2 instances of the same class to another 2 different classes using Spring Framework?


My question is the following: Assume that you have a class Person which has 2 instances Adam and Jacobs. So, you have 2 another classes called School and University. My task is to define by injecting that Jacobs is studying in the school and Adam is an university student as well.

How to do it using Spring Framework? Code written answer is welcome :))


Solution

  • I think what you're trying to do is to inject different instances of the same type in different components. You can do that by using spring @Qualifiers. I sketch a solution to the problem you shared.

    Having the Person class.

    public class Person
    {
        private String name;
    
        public Person(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    }
    

    And a configuration for each person.

    @Configuration
    public class DemoConfig {
    
        @Bean
        public Person adam() {
            return new Person("Adam");
        }
    
        @Bean
        public Person jacobs() {
            return new Person("Jacobs");
        }
    }
    

    The School class.

    @Component
    public class School {
    
        private Person jacobs;
    
        public School(@Qualifier("jacobs") Person jacobs) {
            this.jacobs = jacobs;
        }
    
        public String personName() {
            return jacobs.getName();
        }
    }
    

    The university class is similar to the School class but changing the qualifier name to "adam".

    Here is a test to your requirements.

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class DemoApplicationTests {
    
        @Autowired
        private School school;
    
        @Autowired
        private University university;
    
        @Test
        public void testPersonDependencies() {
            assertThat(school.personName()).isEqualTo("Jacobs");
            assertThat(university.personName()).isEqualTo("Adam");
        }
    }