在使用Spring框架中@Autowired標籤時默認狀況下使用 @Autowired 註釋進行自動注入時,Spring 容器中匹配的候選 Bean 數目必須有且僅有一個。當找不到一個匹配的 Bean 時,Spring 容器將拋出
BeanCreationException 異常,並指出必須至少擁有一個匹配的 Bean。
Spring 容許咱們經過 @Qualifier 註釋指定注入 Bean 的名稱,這樣歧義就消除了,能夠經過下面的方法解決異常。
@Qualifier("XXX") 中的 XX是 Bean 的名稱,因此 @Autowired 和 @Qualifier 結合使用時,自動注入的策略就從 byType 轉變成 byName 了。
@Autowired 能夠對
成員變量、方法以及
構造函數進行註釋,而 @Qualifier 的標註對象是成員變量、方法入參、構造函數入參。
@Autowired
@Qualifier("configSearcherService")
private SearchService service;
@Autowired
@Qualifier("redisService")
private RedisDelegateService redisService;
configSearcherService和redisService已經在配置文件中配置。
applicationContext-services.xml文件部分以下:
<pre name="code" class="html"><?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:amq="http://activemq.apache.org/schema/core"
xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 因爲對同一個collection的查詢對象,各個對象的查詢條件是不可共享的,因此須要多實例運行,scope="prototype"是多實例,不寫該屬性,則爲共享實例 -->
<bean id="configSearcherService" class="com.solr.adjust.service.impl.SearchServiceImpl" scope="prototype"/>
<bean id="redisService" class="com.solr.adjust.service.impl.RedisDelegateService">
在applicationContext-all.xml文件中導入service配置文件
<pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- getContext -->
<bean class="com.solr.adjust.entity.GlobalContext"></bean>
<import resource="applicationContext-services.xml"/>
<import resource="applicationContext-solrConfig.xml"/>
</beans>
在web.xml文件中
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 加載applicationContext-all.xml配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext-all.xml
</param-value>
</context-param>