( 스프링 사용 방법이 아닌 개념에 관한 글입니다 )
예제를 위해 패지키와 클래스를 만들었다.
package spring.di.entity;
public interface Exam {
int total();
float avg();
}
package spring.di.entity;
public class ScoreExam implements Exam {
private int kor;
private int eng;
private int math;
private int com;
public void setKor(int kor) {this.kor = kor;}
public void setEng(int eng) {this.eng = eng;}
public void setMath(int math) {this.math = math;}
public void setCom(int com) {this.com = com;}
@Override
public int total() {return kor + eng + math + com;}
@Override
public float avg() {return total() / 4.0f;}
}
package spring.di.ui;
import spring.di.entity.Exam;
public interface ExamConsole {
void print();
void setExam(Exam exam);
}
package spring.di.ui;
import spring.di.entity.Exam;
public class InlineExamConsole implements ExamConsole {
private Exam exam;
public InlineExamConsole() {}
public InlineExamConsole(Exam exam) {this.exam = exam;}
@Override
public void print() {
System.out.printf("total is %d, avg is %f\n", exam.total(), exam.avg());
}
@Override
public void setExam(Exam exam) {this.exam = exam;}
}
package spring.di.ui;
import spring.di.entity.Exam;
public class GridExamConsole implements ExamConsole {
private Exam exam;
public GridExamConsole() {}
public GridExamConsole(Exam exam) {this.exam = exam;}
@Override
public void setExam(Exam exam) {this.exam = exam;}
@Override
public void print() {
System.out.println("---------- ----------");
System.out.println("| total avg |");
System.out.println("|--------- ---------|");
System.out.printf("| %3d %3.2f |\n", exam.total(), exam.avg());
System.out.println("---------- ----------");
}
}
이제 설명을 위한 Main 클래스이다
package spring.di;
import spring.di.entity.Exam;
import spring.di.entity.ScoreExam;
import spring.di.ui.ExamConsole;
import spring.di.ui.GridExamConsole;
import spring.di.ui.InlineExamConsole;
public class Main {
public static void main(String[] args) {
Exam exam = new ScoreExam();
ExamConsole console = new InlineExamConsole(); // Dependency
// ExamConsole console = new GridExamConsole(); // Dependency
console.setExam(exam); // Injection
console.print();
}
}
인터페이스를 사용해 객체간 느슨한 관계를 형성하였다
그렇지만 때로는 업데이트를 하거나 객체를 다른객체로 변경을 해야하는 경우가 있다
과연 소스코드를 수정하면서 계속해 바꿔주어야 하는것이 맞는 것일까?
기능은 지속적으로 동작할 수 있으면서 소스를 유지한채로 외부에 설정파일을 만들어 실행되도록 해보자
이를 보안하기 위해 XML을 사용해보기로 하자
( 내용이 길어지는 관계로 다음글에서 실습해보자 )
728x90
'Spring' 카테고리의 다른 글
@Autowired, @Qualifier 사용법 (0) | 2023.08.05 |
---|---|
XML 사용법 (0) | 2023.08.05 |
Inversion of Control Container ( Ioc Container ) (0) | 2023.06.14 |
Dependency Injection ( XML ) (0) | 2023.06.14 |
Dependency Injection ( DI ) (0) | 2023.06.13 |