Java:
1.8
javaMaven:
3
springSpringFramework版本以及各組件成員:
5.1.1.RELEASE
this
- spring-context
- spring-core
- spring-beans
可能會有這樣一種狀況,當你建立多個具備相同類型的 bean 時,而且想要用一個屬性只爲它們其中的一個進行裝配,在這種狀況下,你能夠使用 @Qualifier 註釋和 @Autowired 註釋經過指定哪個真正的 bean 將會被裝配來消除混亂。code
Bean.java
package noioo; public class Bean { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
spring-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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <bean id="beanUser" class="noioo.BeanUser"> </bean> <!-- 此處有兩個同類型的Bean, 咱們只要那個"想要的" --> <bean class="noioo.Bean"> <property id="want" name="name" value="想要的Bean!"/> </bean> <bean class="noioo.Bean"> <property name="name" value="不想要的Bean!"/> </bean> <!-- 注意: 類只是個模板, 是"死"的. 只有建立出來的實例對象才具備生命週期.. --> </beans>
BeanUser.java
當不使用
@Qualifier
時, 會顯示報錯(若是你使用的是IDEA):
xml
代碼以下:對象
package noioo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; public class BeanUser { private Bean bean; @Autowired @Qualifier("want") public void setBean(Bean bean) { this.bean = bean; } public Bean getBean() { return bean; } public void useBean(){ System.out.println(bean.getName()); } }
您還能夠改成在方法參數上指定
@Qualifier
註釋blog@Autowired public void setBean(@Qualifier("want")Bean bean) { this.bean = bean; }
Runner.java
package noioo; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Runner { public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml"); BeanUser beanUser = (BeanUser) context.getBean("beanUser"); beanUser.useBean(); } }
想要的Bean! Process finished with exit code 0
BeanUser.java
上述代碼不變, 但修改BeanUser.java
生命週期
package noioo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; public class BeanUser { private Bean bean; @Autowired public BeanUser(@Qualifier("want")Bean bean){ this.bean = bean; } public Bean getBean() { return bean; } public void useBean(){ System.out.println(bean.getName()); } }
想要的Bean! Process finished with exit code 0