스터디📖/Spring

3. 의존 객체 - 2

호프 2021. 7. 5. 15:12

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%ED%94%84%EB%A0%88%EC%9E%84%EC%9B%8C%ED%81%AC_renew/dashboard

 

자바 스프링 프레임워크(renew ver.) - 신입 프로그래머를 위한 강좌 - 인프런 | 강의

스프링 프레임워크 기본부터 실전 사용법까지! 충실하고 폭넓은 설명과 예제를 통해 현장에 바로 투입되어 활약하는 개발자로 거듭나세요., 자바 스프링 프레임워크로 내 개발자 커리어에 봄이

www.inflearn.com

섹션 3 의존 객체

9강 의존객체 자동 주입

9-1 의존객체 자동 주입이란?

스프링 설정 파일에서 의존 객체를 주입할 때 또는 태그로 의존 대상 객체를 명시하지 않아도 스프링 컨테이너가 자동으로 필요한 의존 대상 객체를 찾아서 의존 대상 객체가 필요한 객체에 주입해 주는 기능이다.
구현 방법은 @Autowired 와 @Resource 어노테이션을 이용해서 쉽게 구현할 수 있다.

9-2 @Autowried

주입하려고 하는 객체의 타입이 일치하는 객체를 자동으로 주입한다.

@Autowired
public WordRegisterService(WordDao wordDao){
    this.wordDao = wordDao;
}

 

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    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.xsd 
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />

    <bean id="wordDao" class="com.word.dao.WordDao" />

    <bean id="registerService" class="com.word.service.WordRegisterServiceUseAutowired" />

    <bean id="searchService" class="com.word.service.WordSearchServiceUseAutowired" />

</beans>

property나 method에도@Autowired 사용 가능하지만 이때는 default 생성자를 반드시 명시해 주어야 한다.

9-3 @Resource

주입하려고 하는 객체의 이름이 일치하는 객체를 자동으로 주입한다.
생성자에는 사용 불가. property나 method에만 쓸 수 있음. - default 생성자 반드시 명시해 주어야 함

The import javax.annotation.Resource cannot be resolved 라는 에러가 발생했는데, pom.xml에

<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.1</version>
</dependency>

이걸 추가하니 해결되었다.


10강 의존 객체 선택

다수의 빈(Bean) 객체 중 의존 객체의 대상이 되는 객체를 선택하는 방법

10-1 의존객체 선택

동일한 객체가 2개 이상인 경우 스프링 컨테이너는 자동 주입 대상 객체를 판단하지 못해서 Exception을 발생시킴.

@Autowired -> @Qualifier 사용

<bean id="wordDao1" class="com.word.dao.WordDao" >
	<qualifier value="usedDao"/>
</bean>

 

public class WordRegisterServiceUseAutowired {

	@Autowired
	@Qualifier("usedDao")
	private WordDao wordDao;
    
    public WordRegisterServiceUseAutowired() {
	}
    
    public WordRegisterServiceUseAutowired(WordDao wordDao) {
		this.wordDao = wordDao;
	}
    
    ...
}

 

10-2 의존객체 자동 주입 체크

의존 객체의 대상이 되는 객체가 생성되지 않은 경우 Exception 발생 -> 발생시키지 않도록 하려면 @Autowired(required = false) : 의존 객체가 없으면 주입하지 말아라.

이런 경우 거의 없음.

10-3 @Inject

@Autowired와 거의 비슷하게 의존 객체를 자동으로 주입할 수 있음.
@Autowired의 경우 required 속성을 이용해서 의존 대상 객체가 없어도 Exception을 피할 수 있는데 @Inject의 경우 required 속성을 지원하지 않는다.
@Named(value="wordDao1" Bean 객체의 id명) 를 사용하여 의존 객체를 선택할 수 있음.

@Inject
@Named(value="wordDao1")
private WordDao wordDao;