Sunday, April 19, 2020

[Spring] Dependency Injection

What is dependence?

 Dependencies are relationships in which the processing content of a class changes as the content of another class changes.
예시
public class A {

    B b = new B();
    
    public void methodA() {
     b.methodB();
    }
}
 Class A is invoking a method after creating an object in B to use the method defined in class B. At this time, class A is running a method of class B, which is expressed as A depends on B. If the methodB method contents are changed in this dependency, the contents of A will also be different.

Dependency Injection

 Dependency injection is the way in which objects are passed on and used, rather than created.

example
public class A {
    
    B b;
    
    public A(B b) {
     this.b = b;
    }
    
    public void methodA() {
     b.method();
    }
}
  First, declare a member variable of class A as b and define the constructor that receives the object of class B.

public static void main(String args[]) {
    
    B b = new B();
    A a = new A(b);
}
 As shown above, when you create an object for A and pass the object for B as a factor, you enter the member variable b in class A and use the object.

Reason for injecting dependency

 The advantage of the injection is that it makes it easier to replace the injected object, making it easier to maintain.

public class C extends B {

}
 The advantage of the injection is that it makes it easier to replace the injected object, making it easier to maintain.   

When no dependency injection is used
public class A {

    B b = new C(); // 수정된 부분
    
    public void methodA() {
     b.methodB();
    }
}
  If you have not used dependent injection, you must change one part of the instantiation as above. If you have multiple classes, such as A, you need to correct the instantiation part one by one.

When using dependency injection
public static void main(String args[]) {

    B b = new C(); // 수정된 부분
    A a = new A(b);
    Another aa = new Another(b);
    Other aaa = new Ohter(b);
}
 In the case of a dependency injection, simply replace the object in variable b with C and the change is complete. Even if multiple objects are being injected with B objects, only one modification will allow all Cs to be injected.

No comments:

Post a Comment