티스토리 뷰

스프링설정파일에서 Bean 마다 의존객체를 주입해주게되면 프로그래머가 번거로울 수 있다. 의존객체 주입 방법을 조금 더 편하게 할 수 있는 @Autowired@Resource를 통해 의존객체 자동주입을 알아본다.

 

@Autowired와 @Resource의 차이점을 간단히 살펴보면 다음과 같다.

  @Autowired @Resource
DI 방법 객체 타입 객체 이름
적용가능 범위 - 변수
- 생성자
- Setter
- 메서드
- 변수
- Setter

 

자동주입 사용 전

applicationContext.xml

<bean id="injectionBean" class="scope.ex.InjectionBean" />

<bean id="dependencyBean" class="scope.ex.DependencyBean">
    <constructor-arg ref="injectionBean" />
    <property name="injectionBean" ref="injectionBean" />
</bean>

스프링설정파일 상에서 dependencyBean 클래스에 injectionBean 객체의 생성자와 프로퍼티를 주입해준다.

 

DependencyBean.java

private InjectionBean injectionBean;

public DependencyBean(InjectionBean injectionBean) {
    System.out.println("DependencyBean : constructor"); //생성자 호출 시 출력된다.
    this.injectionBean = injectionBean;
}

public void setInjectionBean(InjectionBean injectionBean) {
    System.out.println("DependencyBean : setter");
    this.injectionBean = injectionBean;
}

** injectionBean 클래스는 코드가 비어있으므로 생략

생성자와 Setter이다. 콘솔창 출력을 통해 해당 메서드 호출을 표시한다.

 

MainClass.java

GenericXmlApplicationContext ctx = 
        new GenericXmlApplicationContext("classpath:applicationContext.xml");

InjectionBean injectionBean = ctx.getBean("injectionBean", InjectionBean.class);

DependencyBean dependencyBean01 = ctx.getBean("dependencyBean", DependencyBean.class);
DependencyBean dependencyBean02 = ctx.getBean("dependencyBean", DependencyBean.class);

if(dependencyBean01 == dependencyBean02) 
    System.out.println("dependencyBean01 == dependencyBean02");
else 
    System.out.println("dependencyBean01 != dependencyBean02");

System.out.println("dependencyBean01 hashcode" + dependencyBean01.hashCode());
System.out.println("dependencyBean02 hashcode" + dependencyBean02.hashCode());

ctx.close();

 

 

 

@Autowired 사용

@Autowired 어노테이션을 생성자 및 메서드에 사용하게 되면, 스프링이 컨테이너에서 타입이 일치하는 Bean을 찾아 의존객체를 주입해준다. 

 

applicationContextAutowired.xml

<bean id="injectionBean" class="scope.ex.InjectionBean" />

<bean id="dependencyBean" class="scope.ex.DependencyBean">
    <!-- <constructor-arg ref="injectionBean" />
    <property name="injectionBean" ref="injectionBean" />  -->
</bean>

context 태그를 이용하기 위해 beans 태그의 네임스페이스와 스키마를 추가해준다.

이후 dependencyBean에 주입해주었던 생성자와 Property를 주석처리해주면 @Autowired를 사용할 준비가 끝난다.

 

DependencyBean.java

public class DependencyBean {
	@Autowired
	private InjectionBean injectionBean; //property
    
    	// property, 메소드에 @Autowired를 적용하기 위해 Default 생성자가 필요
	public DependencyBean() {
	}

	@Autowired
	public DependencyBean(InjectionBean injectionBean) {
		System.out.println("DependencyBean : constructor"); //생성자 호출 시 출력된다.
		this.injectionBean = injectionBean;
	}
	
    	@Autowired
	public void setInjectionBean(InjectionBean injectionBean) {
		System.out.println("DependencyBean : setter");
		this.injectionBean = injectionBean;
	}
	
}

xml 파일의 constructor-arg 태그를 제거한 뒤 @Autowired를 통한 의존객체 자동주입을 하면 같은 결과를 얻을 수 있다.

 

생성자 외에 Property와 메소드에 자동주입을 적용하기 위해선 디폴트 생성자를 반드시 추가해줘야한다. 생성자가 아닌 다른 메소드나 Property에 자동주입이 될 때는 객체가 생성되기 전이므로 InjectionBean을 인자로 받는 생성자를 이용할 수 없기 때문이다.

 

MainClass.java 설정 및 실행결과

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContextAutowired.xml");
DependencyBean : constructor
DependencyBean : setter
dependencyBean01 == dependencyBean02
dependencyBean01 hashcode341796579
dependencyBean02 hashcode341796579

classpath 경로는 새로운 xml 파일경로로 변경해주면 자동주입이 되기 전과 동일한 결과를 얻을 수 있다.

 

@Resource 사용

자동주입을 한다는 점에서 @Autowired와 동일하지만 스프링컨테이너에서 객체를 찾을 때 타입이 아닌 이름으로 객체를 찾는다는점과 생성자엔 사용불가능한 어노테이션이라는 점이 차이있다.

 

DependencyBean.java

@Resource
public DependencyBean(InjectionBean injectionBean) {
    System.out.println("DependencyBean : constructor"); //생성자 호출 시 출력된다.
    this.injectionBean = injectionBean;
}

applicationContextAutowired.xml

<bean id="injectionBean" class="scope.ex.InjectionBean" />

컨테이너 상에 명시한 bean의 id와 생성자의 매개변수로 들어간 변수명이 둘 다 injectionBean으로 일치하기 때문에 DI가 이루어진다.

 

 

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

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함