创建自定义的限定符
我们可以为bean设置自己的限定符,而不是依赖于将bean ID作为限定符.在这里所需要做的就是在bean声明上添加@Qualifier注解来进行更加明确的区分.例如:
Animal接口:
package com.home.quar;
public interface Animal {
public void eat();
}
Cat:
package com.home.quar;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
@Qualifier("cat")
public class Cat implements Animal {
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
Panda:
package com.home.quar;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
@Qualifier("panda")
public class Panda implements Animal {
@Override
public void eat() {
System.out.println("熊猫吃竹子");
}
}
TestDemo:
package com.home.quar;
import org.junit.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TeatDemo {
@Autowired
@Qualifier(value = "cat")
private Animal animal;
public void setAnimal(Animal animal) {
this.animal = animal;
}
public Animal getAnimal() {
return animal;
}
@Test
public void demo() {
ApplicationContext app = new ClassPathXmlApplicationContext("classpath:application.xml");
TeatDemo bean = (TeatDemo) app.getBean("teatDemo");
System.out.println(bean.getAnimal());
Animal al = bean.getAnimal();
if (al instanceof Cat) {
System.out.println("Cat");
} else if (al instanceof Panda) {
System.out.println("Panda");
}
al.eat();
try {
app.getBean("panda");
} catch (Exception e) {
if (e instanceof NoSuchBeanDefinitionException) {
System.out.println("@Qualifier不能作为Bean的标识符");
}
e.printStackTrace();
}
}
}
最终结果是被@Qualifier注解的类被注入了进来,当然我们也可以用 XML配置的方法来限定@Qualifier的注入:
<?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-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" >
<context:annotation-config/>
<bean id="teatDemo" class="com.home.quar.TeatDemo"/>
<bean id="cat" class="com.home.quar.Cat">
<qualifier type="org.springframework.beans.factory.annotation.Qualifier" value="cat"/>
</bean>
<bean id="panda" class="com.home.quar.Panda">
<qualifier type="org.springframework.beans.factory.annotation.Qualifier" value="panda"/>
</bean>
</beans>