Spring프레임워크를 사용하기 위해 꼭 잡고 가야할 개념이 있다..
그것은 바로 DI와 IOC
먼저 DI란
Dependency Injection의 약자로
전략패턴, 의존성 주입 이라고도 합니다.
코드의 수정 없이, 사용하고자 하는 클래스를 주입하고 변경할 수 있게 하는 디자인 패턴입니다.
클래스를 부품화 시킨다.
클래스들의 중복되는 부분(기능)을 interface로 만들고, 그 interface를 상속하여
ex)
class Student {
private MathTest math = new MathTest();
private EnglishTest eng = new EnglishTest();
}
class Student {
private MathTest math;
private EnglishTest eng;
public MathTest getMathTest() {
MathTest math = new MathTest();
return math;
}
public EnglishTest getEnglishTest () {
EnglishTest eng= new EnglishTest ();
return eng;
}
}
위 코드를 아래처럼 바꾸면,
같은 기능을 수행하는 여러 클래스를 동일한 형태로 만들어 사용할 수 있다.
ex)
interface Test {
public void setScore();
public int getScore();
}
class MathTest implements Test {
public void setScore() {
...
}
public int getScore() {
...
return score;
}
}
class EnglishTest implements Test {
public void setScore() {
...
}
public int getScore() {
...
return score;
}
}
class Student {
private MathTest math;
private EnglishTest eng;
public Student(Test test) { //생성자로 클래스 삽입
this.math= test;
}
public void setTest(Test test) {//메소드로 클래스 삽입
this.eng= test;
}
}
IOC
Inversion Of Control의 약자입니다.
일반적인 프로그램은 자신이 사용할 오브젝트를 집적 선택하고 생성합니다.
ex) new TestClass();
하지만 DI를 적용함으로서, TestClass를 사용하고자 하는 클래스를 수동적으로 만들어 주었다.
ex)
class a {
private TestClass test
public a(TestClass testclass) {
this.test = testclass;
}
}
or
class a {
private TestClass test
public void setClass(TestClass testclass) {
this.test = testclass;
}
}
참고 : http://joont.tistory.com/135