3-3 ~ 3-8 Spring DI

서현우·2022년 5월 30일
0

복습

목록 보기
25/34

1. 빈(Bean)이란?

JavaBeans
재사용 가능한 컴포넌트, 상태(iv), getter&setter, no-args constructor

Servlet&JSP bean
MVC의 Model, EL, scope, JSP container가 관리

EJB

Spring Bean - POJO. 단순, 독립적, Spring container가 관리

2. BeanFactory, ApplicationContext

Bean - Spring Container가 관리하는 객체

Spring container - Bean저장소, Bean을 저장, 관리(생성, 소멸, 연결)
1.BeanFactory - Bean을 생성, 연결 등의 기본 기능을 정의(인터페이스)
2.ApplicationContext - BeanFactory를 확장해서 여러 기능을 추가 정의

4. ApplicationContext(AC)의 종류

  1. XML설정()
  • non-Web : GenericXmlApplicationContext
  • Web : XmlWebApplicationContext
  1. Java Config설정(@Bean)(자바코드를 쓰므로 컴파일러 사용 가능)
  • non-Web : AnnotationConfigApplicationContext
  • Web : AnnotionConfigWebApplicationContext

4. Root AC, Servlet AC

5. ApplicationContext의 주요 메서드

getBean() //빈 얻기
isPrototype()
isSingleton()
isTypeMatch()
containsBean()
findAnnotationOnBean()
getBeanDefinitionCount() //정의된 빈의 개수
getBeanDefinitionNames() //정의된 빈의 이름

6. IoC와 DI

제어의 역전 IoC

  • 제어의 흐름을 전통적인 방식과 다르게 뒤바꾸는 것
    의존성 주입 DI
  • 사용할 객체를 외부에서 주입받는 것
//전통적인 방식 : 사용자 코드가 Framework코드를 호출
Car car = new Car();
car.turboDrive(); //호출

void turboDrive() {
	engine=new TurboEngine();
	engine.start();
}

//IoC : Framework코드가 사용자 코드를 호출
//디자인 패턴의 전략패턴
Car car = new Car();
car.drive(new SuperEngine());

//DI - new SuperEngine()을 수동 주입.
void drive(Engine engine) {
	engine.start(); //호출
}

7. @Autowired

인스턴스 변수(iv), setter, 참조형 매개변수를 가진 생성자, 메서드에 적용

//iv
class Car {
	@Autowired Engine engine;
	@Autowired Engine[] engines;
	
	@Autowired(required=false)
	SuperEngine superEngine;
}

//참조형 매개변수를 가진 생성자
//생성자의 @Autowired는 생략 가능.
//가능하면 주입 받아야 할 bean들을 다 적은 생성자로 주입받는게 유리.
@Autowired
public Car(@Value("red") String color, @Value("100") int oil, Engine engine, Door[] doors) {
	this.color=color;
	this.oil=oil;
	this.engine=engine;
	this.doors=doors;
}

//setter, 메서드
@Autowired
public void setEngineAndDoor(Engine engine, Door[] doors){
	this.engine=engine;
	this.doors=doors;
}

@Autowired는
Spring container에서 타입으로 빈을 검색해서 참조변수에 자동 주입(DI).
검색된 빈이 n개이면, 그 중에 참조변수와 이름이 일치하는 것을 주입.
주입 대상이 변수일 때, 검색된 빈이 1개가 아니면 예외 발생.
주입 대상이 배열일 때, 검색된 빈이 n개라도 예외 발생X.
(But @Autowired(required=false)일 때, 주입할 빈을 못찾아도 예외발생X.)

@Resource

Spring container에서 이름으로 빈을 검색해서 참조 변수에 자동 주입(DI)
일치하는 이름의 빈이 없으면 예외발생

class Car {
	@Resource(name="superEngine")
	Engine engine;
}
class Car{
	//@Resource(name="engine")
	//이름을 지정안하면 참조변수명으로 검색
	@Resource
	Engine engine;
}
class Car {
	//타입으로 검색후, 값이 여러개면 이름으로 검색
	@Autowired
	@Qualifier("superEngine")
	Engine engine;
}

@Component

으로 @Component가 클래스를 자동 검색해서 빈으로 등록.
@Controller, @Service, @Repository, @ControllerAdvice의 메타 애너테이션

<context:component-scan base-package="com.fastcampus.ch3"/>
//<bean id="superEngine" class="com.fastcampus.ch3.SuperEngine"/>
//@Component("superEngine")
@Component
class SuperEngine extends Engine {}

@Value와 @PropertySource

@Component
@PropertySource("setting.properties")
class SysInfo {
	@Value("#{systemProperties['user.timezone']}")
	String timeZone;
	
	@Value("#{systemEnvironment['PWD']}"
	String currDir;
	
	@Value("${autosaveDir}")
	String autosaveDir;
	
	@Value("${autosaveInterval}")
	int autosaveInterval;
	
	@Value("${autosave}")
	boolean autosave;
}
//[src/main/reousrces/setting.properties]
autosaveDir=autosave
autosave=true
autosaveInterval=30

스프링 애너테이션 vs 표준 애너테이션

  1. 스프링
    @Autowried, @Qualifier, @Scope("singleton"), @Component

  2. 표준
    @Resource

빈의 초기화

<property>와 setter
<list>, <set>, <map>

profile
안녕하세요!!

0개의 댓글