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

前端 未结 11 2448
你的背包
你的背包 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:33

    IOC stands for inversion of control and is a higher level concept that states that we invert the control of the creation of objects from the caller to the callee.

    Without inversion of control, you are in charge of the creation of objects. In an inversion of control scenario a framework is in charge to create instances of a class.

    Dependency injection is the method through which we can achieve inversion of control. In order for us to leave the control up to the framework or job we declare dependencies and the IOC container injects those dependencies in our class (i.e. the framework creates an instance for us and provides that to our class).

    Now what are the advantages of this?

    First of all the classes and their lifecycle will be managed by Spring. Spring completely manages the process from creation to destruction.

    Secondly, you will get reduced coupling between classes. A class is not tightly coupled with an implementation of another class. If an implementation changes, or if you want to change the implementation of the injected interface you can do so easily without needing to change all the instances in your code base by hand.

    Third, there is an increased cohesion between classes. High cohesion means keeping classes that are associated with one another together. Because we are injecting interfaces in other classes it is clear which classes are necessary for the calling class to operate.

    Fourth, there is increased testability. Because we are using interfaces in the constructor we can easily swap out the implementation with a mock implementation

    fifth, the use of JDK dynamic proxy to proxy objects. the JDK dynamic proxy requires interfaces to be used which is true, because we are injecting these interfaces. This proxy can then be used for Spring AOP, transaction handling, Spring data, Spring security and more

提交回复
热议问题