@Autowired 애노테이션 

생성자, 필드(프로퍼티), 설정메서드(set메서드)에 지정 가능

타입을 이용해서 자동적으로 프로퍼티 값을 설정하기 때문에 해당 타입의 빈 객체가 존재하지 않거나 빈 객체가 두 개 이상 존재할 경우 예외 발생.


@Autowired 애노테이션 예외 발생

해당 타입의 빈 객체가 존재하지 않거나 빈 객체가 두 개 이상 존재할 경우 예외가 발생한다.


1. 해당 타입의 빈 객체가 존재하지 않는 경우 예외 처리

@Autowired(required=false)로 지정: 기본값은 @Autowired(required=true)

false로 하면 빈 객체가 존재하지 않더라도 예외처리를 발생시키지 않는다.


2. 동일한 타입의 빈 객체가 두 개 이상 존재하는 경우 예외 처리

@Qualifier("설정파일에서 지정한 값")으로 지정


주의) 설정 메서드에서 @Autowired를 사용시 동일 타입의 객체가 2개 이상 있을 경우 스프링 버전을 필히 확인(Ver. 3.2.3까지는 에러 발생).



예제1) @Autowired : required=false 사용


1) UseClass 클래스

package spring.anno.ch02;


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


public class UseClass {

private ImpClass impl;

@Autowired(required=false)  // required를 false로 하여 주입 안받아도 예외처리 하지 않도록 함.

public void setImpl(ImpClass impl){

this.impl = impl;

}

// Autowired는 setter 메서드의 타입(ImpClass)을 보고 

// ImpClass에 가서 bean 객체를 가져오게 된다.

public ImpClass getImpl(){

return impl;

}

public void implCall(){

System.out.println("UseClass 실행");

this.impl.display();

}

}



2) ImpClass 클래스

package spring.anno.ch02;


public class ImpClass {

public void display(){

System.out.println("ImpClass 실행");

}

}



3) 실행 클래스

package spring.anno.ch02;


import org.springframework.context.support.AbstractApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Main {


public static void main(String[] args) {

AbstractApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml");

factory.registerShutdownHook();


UseClass useClass = factory.getBean("useClass", UseClass.class);

useClass.implCall();


factory.close();

}

}



4) 설정 파일

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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-3.2.xsd">

<!-- 1차: 설정 파일에서 멤버 변수를 초기화
<bean id="useClass" class="spring.anno.ch02.UseClass">
  <property name="impl" ref="impClass" /> 
</bean>
 -->

<context:annotation-config />
<!-- 2차: @Autowired 사용. 주입받는 객체의 타입을 보고 프로퍼티 자동으로 가져옴. -->
<bean id="useClass" class="spring.anno.ch02.UseClass"></bean>
<bean id="impClass" class="spring.anno.ch02.ImpClass"></bean>
</beans>







예제2) 2개 이상의 타입이 있을 때의 @Autowired


1) 위 예제의 설정 파일에서 같은 타입의 객체를 하나 더 만든다.


<!-- 2차 : @Autowired 어노테이션 적용 : 타입으로 자동 초기화(주입) -->

<bean id="useClass" class="spring.anno.ch02.UseClass" />

<bean id="impClass" class="spring.anno.ch02.ImpClass" />

<bean id="impl" class="spring.anno.ch02.ImpClass" />

<!-- 동일한 ImpClass 객체가 2개 생성됨 -->



2) 위 예제의 UseClass에서 다음과 같이 해본다.


package spring.anno.ch02;


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


public class UseClass {

@Autowired // 기본은 타입을 보고 찾지만 같은 타입이 있으면 다음은 이름으로 찾아 자동으로 주입된다.

private ImpClass impl;

public void setImpl(ImpClass impl){

this.impl = impl;

}

public ImpClass getImpl(){

return impl;

}

public void implCall(){

System.out.println("UseClass 실행");

this.impl.display();

}

}


※ 스프링 최신 버전에서는 객체 타입이 2개 있어도 @Autowired가 타입 대신 이름으로 찾아 주입한다.
하지만 3.2.16 이전 버전에서는 에러가 난다.




예제3) @Autowired, @Qualifier 사용


1) Executor 클래스


package spring.anno.ch03;


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

import org.springframework.beans.factory.annotation.Qualifier;


public class Executor {


private Worker worker;

@Autowired

@Qualifier("main") // 설정파일 Qualifier에서 설정한 main이름이 부여된 빈 객체를 가져온다.

public void setWorker(Worker worker) {

this.worker = worker;

}

public Worker getWorker() {

return worker;

}

public void WorkerCall() {

System.out.println("Excutor 클래스 실행");

worker.display();

}

}



2) Worker 클래스

package spring.anno.ch03;

public class Worker {

public void display() {
System.out.println("Worker 클래스 실행");
}
}


3) 실행 클래스


package spring.anno.ch03;


import org.springframework.context.support.AbstractApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;


import spring.anno.ch02.UseClass;


public class Main {


public static void main(String[] args) {

AbstractApplicationContext factory = 

new ClassPathXmlApplicationContext("applicationContext.xml");

factory.registerShutdownHook();


Executor executor = 

factory.getBean("executor", Executor.class);

executor.WorkerCall();

factory.close();


}


}



4) 설정 파일

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

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

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-3.2.xsd">

<!-- ch03 -->

<bean id="executor" class="spring.anno.ch03.Executor" />

<bean id="worker" class="spring.anno.ch03.Worker" />

<bean id="worker2" class="spring.anno.ch03.Worker">

<qualifier value="main" />

</bean>

</beans>








Posted by netyhobby
,