What is Dependency Injection and Inversion of Control in Spring Framework?

前端 未结 11 2400
你的背包
你的背包 2020-12-02 03:51

\"Dependency Injection\" and \"Inversion of Control\" are often mentioned as the primary advantages of using the Spring framework for developing Web frameworks

Could

11条回答
  •  [愿得一人]
    2020-12-02 04:34

    Inversion of control- It means giving the control of creating and instantiating the spring beans to the Spring IOC container and the only work the developer does is configuring the beans in the spring xml file.

    Dependency injection-

    Consider a class Employee

    class Employee { 
       private int id;
       private String name;
       private Address address;
    
       Employee() {
         id = 10;
         name="name";
         address = new Address();
       }
    
    
    }
    

    and consider class Address

    class Address {
       private String street;
       private String city;
    
       Address() {
         street="test";
         city="test1";
    
      }
    }
    

    In the above code the address class values will be set only when the Employee class is instantiated, which is dependency of Address class on Employee class. And spring solves this problem using Dependency Injection concept by providing two ways to inject this dependency.

    1. Setter injection

    Setter method in Employee class which takes a reference of Address class

    public void setAddress(Address addr) {
        this.address = addr;
    }
    
    1. Constructor injection

    Constructor in Employee class which accepts Address

    Employee(Address addr) {
          this.address = addr;
    }
    

    In this way the Address class values can be set independently using either setter/constructor injection.

提交回复
热议问题