Home > AI > Backend > SpringBoot >

Inversion of Control

If we have two classes and one is dependent on another class. When we want to initiate the first one, we have initiated its related classes which may be troublesome.

Address address = new Address("High Street", 1000);
Company company = new Company(address);

So, we introduce Inversion of Control that we assumes dependent attributes have default values.

Example codes

Company.java

@Data
@Component
public class Company {
    private Address address;

    public Company(Address address) {
        this.address = address;
    }
}

Address.java

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Address {
    private String street;
    private int number;

}

Config.java

@Configuration
@ComponentScan(basePackageClasses = Company.class)
public class Config {
    @Bean
    public Address getAddress() {
        return new Address("High Street", 1000);
    }
}

SpringBeanIntegrationTest.java

public class SpringBeanIntegrationTest {
    @Test
    public void whenUsingIoC_thenDependenciesAreInjected() {
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        Company company = context.getBean("company", Company.class);
        assertEquals("High Street", company.getAddress().getStreet());
        assertEquals(1000, company.getAddress().getNumber());
    }
}

Leave a Reply