백엔드/Spring

Spring - DI 실습 | TIL_148

ran4 2022. 9. 30. 20:28

https://www.youtube.com/playlist?list=PLq8wAnVUcTFUHYMzoV2RoFoY2HDTKru3T

스프링 강의를 듣고 정리한 내용입니다

 


실습

Dependency를 직접 Injection하기

-> 부품을 조립하는 과정을 실습한다

 

 

 

DI를 위한 프로젝트 생성 – 성적계산 프로그램

실행을 위한 Program 클래스 생성

package spring.di;

public class Program {
public static void main(String[] args) {

//Entity 클래스
Exam exam = new NewlecExam();

//출력 클래스
ExamConsole console = new InlineExamConsole(exam);
console.print();
}
}

 

 

Exam 인터페이스 생성

package spring.di.entity;

public interface Exam {
int total();
float avg();
}

 

 

Entity 클래스 생성

package spring.di.entity;

public class NewlecExam implements Exam {
private int kor;
private int eng;
private int math;
private int com;

@Override
public int total() {
return kor + eng + math + com;
}

@Override
public float avg() {
return total() / 4.0f;
}
}

 

 

콘솔 ui 인터페이스 생성

package spring.di.ui

public interface ExamConsole {
void print();
}

 

 

인터페이스를 구현하는 클래스 생성

package spring.di.ui

public class InlineExamConsole implements ExamConsole {

private Exam exam;

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());
}

 

실행결과 : total is 0, avg is 0.0000

 

 

 

Grid 형태로 출력하기

Program 코드 수정 

package spring.di;

public class Program {
public static void main(String[] args) {

//Entity 클래스
Exam exam = new NewlecExam();

//출력 클래스 – 그리드
ExamConsole console = new GridExamConsole(exam);
console.print();
}
}

 

 

GridExamConsole 구현

package spring.di.ui


public class GridExamConsole implements ExamConsole {

private Exam exam;

public GridExamConsole(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("└─────────┴─────────┘");
}

 

 

Program의 코드에서 

 

ExamConsole console = new InlineExamConsole(exam); 

-> 객체를 조립한다 == DI

DI를 사용하면 콘솔 출력을 바꿀 수 있다 -> Spring(외부설정)을 이용하면 간편하게 가능하다

 

 


 

 

Spring DI를 위한 이클립스 플러그인 설치

  • 변경을 할 때는 설정을 따로 분리하는 것이 좋다
  • 직접 선언할 수 있고 플러그인을 이용할 수도 있다

 

 

xml로 설정하는 방법

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

</beans>

 

이 방법은 보통 이미 설정된 것을 복붙해서 사용한다

-> 설정하기엔 코드가 길어 강의에선 추천하지 않는 방법이다

 

 

 

이클립스 플러그인 - STS를 사용한다

marketplace > spring 검색 > sts install

  • sts 3 > 스프링을 기반으로 하는 프로젝트
  • sts 4 > 스프링 부트를 기반으로 하는 프로젝트

-> 해당 강의에서는 3을 설치한다

반드시 필요한 IDE는 아니지만, 설정이 번거롭기 때문에 사용한다

 

설치 후 New > Other > Spring Bean Configuration File 선택 후

setting.xml 을 입력하여 추가