Anda di halaman 1dari 5

Autowire Annotation using Qualifier:

Address.java
package com.app.model;

public class Address {

private int doorId;

public int getDoorId() {


return doorId;
}

public void setDoorId(int doorId) {


this.doorId = doorId;
}

==
Employee.java
package com.app.model;

import
org.springframework.beans.factory.annotation.Aut
owired;
import
org.springframework.beans.factory.annotation.Qua
lifier;

public class Employee {


@Autowired
@Qualifier("abcd")
private Address address;

public Employee() {
super();
}

public Employee(Address address) {


super();
this.address = address;
}

public Address getAddress() {


return address;
}

public void setAddress(Address address) {


this.address = address;
}

}
= =
beans.xml
<beans
xmlns="http://www.springframework.org/schema/bea
ns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xmlns:p="http://www.springframework.org/schema/p
"
xmlns:c="http://www.springframework.org/schema/c
"
xmlns:context="http://www.springframework.org/sc
hema/context"
xsi:schemaLocation="http://www.springframework.o
rg/schema/beans
http://www.springframework.org/schema/beans/spri
ng-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/sp
ring-context-3.0.xsd">

<context:annotation-config/>
<bean id="employee"
class="com.app.model.Employee">
</bean>
<bean id="abcd"
class="com.app.model.Address">
<property name="doorId" value="8585"/>
</bean>
<bean id="mnop"
class="com.app.model.Address">
<property name="doorId" value="9589"/>
</bean>
</beans>
= =
Test.java
package com.app.test;

import
org.springframework.context.support.AbstractAppl
icationContext;
import
org.springframework.context.support.ClassPathXml
ApplicationContext;

import com.app.model.Employee;

public class Test {

public static void main(String[] args) {


AbstractApplicationContext context=new
ClassPathXmlApplicationContext("beans.xml");
Employee
employee=context.getBean("employee",
Employee.class);

System.out.println(employee.getAddress().getDoor
Id());

}
===
Output:

Anda mungkin juga menyukai