Three ways of dependency injection

Dependency injection: Alias ​​for IOC. Dependency injection is the implementation of IOC. The essence of IOC is to transfer the creation of objects from the program to the container. Dependency injection is the way to achieve this goal.

(1) Constructor injection: that is, the injected object can let the outside (usually the IOC container) know which dependent objects it needs by declaring the parameter list of the dependent object in its constructor, and then the IOC container will check the construction of the injected object method to 
get the list of dependent objects it needs, and then inject the corresponding objects into it.

(2) Setter method injection: that is, the current object only needs to add setter methods to the properties corresponding to its dependent objects. The IOC container uses this setter method to set the corresponding dependent objects to the injected object, that is, setter method injection.

(3) Interface injection: Interface injection is a bit complicated. If the injected object wants the IOC container to inject dependent objects for it, it must implement an interface. This interface provides a method to inject dependent objects into the injected object. The IOC container The dependent object is injected into the injected object through the interface method. Compared with the first two injection methods, interface injection is more cumbersome and rigid, and the injected object must declare and implement another interface.

A simple example of interface injection: A Person object depends on a User object through interface injection. The following operations are required: 
(a) Create the interface to be implemented by Person (the injected object):

interface UserInject{
        void injectUser(User user);//这里必须 是被注入对象依赖的对象
    }
  • 1
  • 2
  • 3

(b) The Person object implements the interface

class Person implements UserInject{
        private User user;

        public Person(){}

        @Override
        public void injectUser(User user){
            this.user = user;//实现注入方法,外部通过此方法给此对象注入User对象
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

(c) Externally call the injectUser method to inject the User object into the Persion object, which is interface injection

So: the IOC container plays the role of binding the injected object with the objects that the injected object depends on

Therefore: the responsibilities of the IOC container: (1) Dependent object construction and management of business objects (2) Binding of business objects and dependent objects

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325989597&siteId=291194637