파게로그
Spring 없이 직접 DI를 한다면? Spring의 역할 본문
admin.school.Program
package admin.school;
import admin.school.entity.Exam;
import admin.school.entity.MidTermExam;
import admin.school.ui.ExamConsole;
import admin.school.ui.InlineExamConsole;
import admin.school.ui.TableExamConsole;
public class Program {
public static void main(String[] args) {
Exam exam = new MidTermExam(60, 70, 40, 80);
ExamConsole inlineExamConsole = new InlineExamConsole(exam); // DI
inlineExamConsole.print();
}
}
admin.school.entity.Exam
package admin.school.entity;
public interface Exam {
int sum();
double avg();
}
admin.school.entity.MidTermExam
package admin.school.entity;
public class MidTermExam implements Exam {
int kor;
int eng;
int math;
int com;
public MidTermExam(int kor, int eng, int math, int com) {
this.kor = kor;
this.eng = eng;
this.math = math;
this.com = com;
}
@Override
public int sum() {
return kor + eng + math + com;
}
@Override
public double avg() {
return (kor + eng + math + com) / 4.0;
}
}
admin.school.ui.ExamConsole
package admin.school.ui;
import admin.school.entity.Exam;
public interface ExamConsole {
void print();
void setExam(Exam exam);
}
admin.school.ui.InlineExamConsole
package admin.school.ui;
import admin.school.entity.Exam;
public class InlineExamConsole implements ExamConsole {
Exam exam;
public InlineExamConsole() {
}
public InlineExamConsole(Exam exam) {
this.exam = exam;
}
@Override
public void print() {
System.out.printf("Sum: %d, Avg: %.2f\n", exam.sum(), exam.avg());
}
@Override
public void setExam(Exam exam) {
this.exam = exam;
}
}
admin.school.ui.TableExamConsole
package admin.school.ui;
import admin.school.entity.Exam;
public class TableExamConsole implements ExamConsole {
Exam exam;
public TableExamConsole() {
}
public TableExamConsole(Exam exam) {
this.exam = exam;
}
@Override
public void print() {
System.out.printf("┌─────┬──────────┐\n");
System.out.printf("│ Sum │ %5d │\n", exam.sum());
System.out.printf("│ Avg │ %5.2f │\n", exam.avg());
System.out.printf("└────────────────┘\n");
}
@Override
public void setExam(Exam exam) {
this.exam = exam;
}
}
그런데, InlineExamConsole을 사용하고 있는 지금, 만약 GridExamConsole을 새로 만들었다면 어떻게 해야 할까? 우리는 코드를 수정하지 않고서도 객체를 생성하는 부분을 바꿀 수 있어야 한다. 이 때 해당 바꾸는 부분들을 외부 설정 파일로 따로 작성하고 설정하는 것을 Spring이 도와준다.
'콤퓨타 왕기초 > Spring' 카테고리의 다른 글
annotation을 이용한 객체 생성 (0) | 2021.04.20 |
---|---|
Annotation을 이용할 때의 장점과 @Autowired 를 이용한 DI (0) | 2021.04.15 |
Spring Bean configuration (0) | 2021.04.14 |
Dependency Injection, IoC Container (0) | 2021.04.12 |
Spring Framework (0) | 2021.04.12 |
Comments