반응형
Spring @Qualifier Annotation
(원문 위치 : http://www.tutorialspoint.com/spring/spring_qualifier_annotation.htm )
동일 타입의 하나이상의 bean을 생성하고 속성(property)으로 그중 단지 하나와 wire되기를 원하는 상황이 있을 것이다. 이러한 경우 @Autowired와 함께 @Qualifier annotation을 사용하여 wire되어질 정확한 bean을 명시하여 혼란을 제거한다. 아래 예제는 @Qualifier의 예제이다.
Example:
[003] HelloWorld Exampe 강좌를 참조하여 프로젝트를 생성한다.
Student.java:
package com.tutorialspoint; public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } public void setName(String name) { this.name = name; } public String getName() { return name; } }
Profile.java: student 속성(property)에 @Autowired 속성을 사용하였고, 또한 @Qualifier 속성으로 student1 bean정의를 사용하여 속성을 생성할 것을 나타내고 있다.
package com.tutorialspoint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; public class Profile { @Autowired @Qualifier("student1") private Student student; public Profile(){ System.out.println("Inside Profile constructor." ); } public void printAge() { System.out.println("Age : " + student.getAge() ); } public void printName() { System.out.println("Name : " + student.getName() ); } }
MainApp.java:
package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); Profile profile = (Profile) context.getBean("profile"); profile.printAge(); profile.printName(); } }
Beans.xml:
<?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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config/> <!-- Definition for profile bean --> <bean id="profile" class="com.tutorialspoint.Profile"> </bean> <!-- Definition for student1 bean --> <bean id="student1" class="com.tutorialspoint.Student"> <property name="name" value="Zara" /> <property name="age" value="11"/> </bean> <!-- Definition for student2 bean --> <bean id="student2" class="com.tutorialspoint.Student"> <property name="name" value="Nuha" /> <property name="age" value="2"/> </bean> </beans>
실행 결과는 아래와 같다.
Inside Profile constructor. Age : 11 Name : Zara
반응형