상세 컨텐츠

본문 제목

Dependency Injection 복습1) Constructor Injection

Spring

by 빙하둘리 2022. 12. 19. 23:52

본문

728x90

Autowiring Example

Injecting FortuneService into a Coach implementations

스프링은 @Components를 스캔한다.

FortuneService 인터페이스를 구현할 애 있니?

있어! 그게 HappyFortuneService야~

 

참고 글

https://mangkyu.tistory.com/150

 

[Spring] 의존성 주입(Dependency Injection, DI)이란? 및 Spring이 의존성 주입을 지원하는 이유

1. 의존성 주입(Dependency Injection)의 개념과 필요성 [ 의존성 주입(Dependency Injection) 이란? ] Spring 프레임워크는 3가지 핵심 프로그래밍 모델을 지원하고 있는데, 그 중 하나가 의존성 주입(Dependency Inj

mangkyu.tistory.com

 

 

 

 

 

어느 책에서 의존성은 new라고 했다.

 

 

Dependency Injection 종류 3가지

Constructor

Setter

Field Injection

 

 

일단, Constructor Injection부터 해보자.

1. dependency interface와 class 정의

File: FortuneService.java

public interface FortuneService {
	public String getFortune();
}

 

File: HappyFortuneService.java

@Component
public class HappyFortuneService implements FortuneService {

	public String getFortune() {
    	return "Today is your lucky day!";
    }
}

 

Step2: Create a constructor in your class for injections

File: TennisCoach.java

@Component
public class TennisCoach implements Coach {

	private FortuneService fortuneService;
    
    public TennisCoach(FortuneService theFortuneService) {
    	fortuneService = theFortuneService;
    }
    ...
 }

 

Step3: Configure the dependency injection @Autowired annotation

@Component
public class TennisCoach implements Coach {

	private FortuneService fortuneService;
    
    @Autowired
    public TennisCoach(FortuneService theFortuneService) {
    	fortuneService = theFortuneService;
    }
    ...
 }

FortuneService를 TennisCoach 생성자의 인자로 주입(장착)하는 형태

 

 

예시 코드

인터페이스 Coach와 FortuneService

Coach.java

package com.luv2code.springdemo;

public interface Coach {

	public String getDailyWorkout();

	public String getDailyFortune();
	
}

 

FortuneService.java

package com.luv2code.springdemo;

public interface FortuneService {

	public String getFortune();
	
}

위의 인터페이스를 구현한 코드

 

FortuneService.java

package com.luv2code.springdemo;

import org.springframework.stereotype.Component;

@Component
public class HappyFortuneService implements FortuneService {

	@Override
	public String getFortune() {
		return "Today is your lucky day!";
	}

}

 

TennisCoach.java

package com.luv2code.springdemo;

import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
public class TennisCoach implements Coach {

	private FortuneService fortuneService;
	
	@Autowired
	public TennisCoach(FortuneService theFortuneService) {
		fortuneService = theFortuneService;
	}

	@Override
	public String getDailyWorkout() {
		return "Practice your backhand volley";
	}

	@Override
	public String getDailyFortune() {
		return fortuneService.getFortune();
	}

}

 

 

main 함수를 포함한 데모 코드

package com.luv2code.springdemo;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AnnotationDemoApp {

	public static void main(String[] args) {

		// read spring config file
		ClassPathXmlApplicationContext context = 
				new ClassPathXmlApplicationContext("applicationContext.xml");
		
		// get the bean from spring container
		Coach theCoach = context.getBean("tennisCoach", Coach.class);
		
		// call a method on the bean
		System.out.println(theCoach.getDailyWorkout());

		// call method to get daily fortune
		System.out.println(theCoach.getDailyFortune());
				
		// close the context
		context.close();
		
	}

}

 

@Autowired를 하면 스프링은 scan for a component that implement FortuneService interface

our example) HappyFortuneService

 

즉, Autowired하면 XML 파일 설정 필요 없이 거기에 걸맞는 interface를 구현하는 클래스를 넣어준다.

기존의 property 머시기, ref 머시기, constructor arg 머시기 이런 xml 설정이 사라졌다!

 

 

@Component, @Autowired, @Qualifier의 역할은?

 

참고자료

https://galid1.tistory.com/512

 

Spring - @Autowired 분석!

Spring @Autowired어노테이션이란 @Autowired에 대한 분석이라기에는 얕은 지식을 가지고 @Autowired어노테이션에 관해서 포스팅을 해보겠습니다. 1. Autowired란?@Autowired어노테이션은 이름을 보면 알 수 있

galid1.tistory.com

다시 읽어보기

728x90

'Spring' 카테고리의 다른 글

@Controller, @RequestMapping 복습 글  (0) 2022.12.27
비즈니스 로직이란?  (0) 2022.12.21
jar 파일, war 파일, apk  (0) 2022.12.03
postman 초간단 사용 방법  (1) 2022.11.27
[Spring] Repository에 대한 설명  (0) 2022.11.27

관련글 더보기

댓글 영역