Spring - Qualifier
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.16</version>
</dependency>
Sample Program for @Qualifier using 'Spring Framework'
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="engineModel1" class="com.ah.di.Engine">
<property name="engineModel" value="Model-1"/>
</bean>
<bean id="engineModel2" class="com.ah.di.Engine">
<property name="engineModel" value="Model-2"/>
</bean>
<bean id="car" class="com.ah.di.Car" />
</beans>
package com.ah.di;
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("beans_di.xml");
Car car = context.getBean("car",Car.class); car.checkCarEngine(); }
}
package com.ah.di;
import org.springframework.beans.factory.annotation.Autowired import or.springframework.beans.factory.annotation.Qualifier;
public class Car {
@Autowired @Qualifier("engineModel2") private Engine engine;
public void checkCarEngine(){ if(engine!=null){ engine.testEngine(); }else{ System.out.println("Engine is dead"); } } }
package com.ah.di;
public class Engine { public void testEngine(){ System.out.println("engine is working" ); } }
No comments:
Post a Comment