The @Qualifier annotation

You might create an excess of one bean of a similar type and need to wire just a single one of them with the property. In such cases, you can utilize the @Qualifier annotation alongside @Autowired to evacuate the disarray by determining which correct bean will be wired. In this section, we'll look at a precedent to demonstrate the utilization of a @Qualifier annotation.

The content of the bean.xml configuration file is as follows:

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

<context:annotation-config/> <!--after this tag, you have to write the beans-->

<!-- Definition for Fighters bean without constructor-arg -->
<bean id="fighters" class="qualifierAnnotation.Fighters"/>

<!--fighter 1-->
<bean id="fighter1" class="qualifierAnnotation.UsersForQualifier">
<property name="name" value="Naruto Uzumaki"/>
<property name="village" value="Konohagakure"/>
</bean>

<!--fighter 2-->
<bean id="fighter2" class="qualifierAnnotation.UsersForQualifier">
<property name="name" value="Gaara"/>
<property name="village" value="Sunagakure"/>
</bean>
</beans>

Here's the content of AnnotationBasedQualifierApp.kt:

fun main(args: Array<String>) {
val context = ClassPathXmlApplicationContext("qualifierAnnotation/beans_for_qualifier.xml")
val fighters = context.getBean("fighters") as Fighters
fighters.getName()
fighters.getVillage()
}

Now, add another class. Here's the content for UsersForQualifier.kt:

class UsersForQualifier{
private var village: String? = null
private var name: String? = null

fun setVillage(village: String?) {
this.village = village
}

fun getVillage(): String? {
return village
}

fun setName(name: String) {
this.name = name
}

fun getName(): String? {
return name
}
}

Finally, add the Fighters.kt class. Here's the content of this class:

class Fighters {
@Autowired
@Qualifier("fighter1")
lateinit var usersForQualifier: UsersForQualifier

init {
println("Fighters constructor.")
}

fun getName() {
println("Name: " + usersForQualifier.getName())
}

fun getVillage() {
println("Village: " + usersForQualifier.getVillage())
}
}

If you run the output, it will be as follows: 

Fighters constructor.
Name: Naruto Uzumaki
Village: Konohagakure

Modify the qualifier value like so:

 @Qualifier("fighter2")

It will create the following output: 

Fighters constructor.
Name: Gaara
Village: Sunagakure
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.172.115