在Spring从自动装配中排除Bean
时间:2020-01-09 10:44:28 来源:igfitidea点击:
如果我们想在每个豆的基础上排除在Spring中自动装配bean,那么以Spring的XML格式,可以通过将<bean />元素的autowire-candidate属性设置为false来完成。 Spring容器使该特定的bean定义不可用于自动装配(这也适用于注释样式配置,例如@Autowired)。
自动装配中不包括Bean –自动接线候选示例
在该示例中,有一个用于下订单的类称为OrderService,可以从商店进行购买。在OrderService类中,必须自动关联商店的依赖关系。
有两种类型为IStore的类,我们想从自动装配中排除其中一个bean,以便不引发NoUniqueBeanDefinitionException。
public interface OrderService {
public void buyItems();
}
import org.springframework.beans.factory.annotation.Autowired;
public class OrderServiceImpl implements OrderService {
private IStore store;
@Autowired
public OrderServiceImpl(IStore store){
this.store = store;
}
public void buyItems() {
store.doPurchase();
}
}
如我们所见,OrderServiceImpl类具有类型为Istore的依赖项,该依赖项会自动构造为构造函数参数。
public interface IStore {
public void doPurchase();
}
public class RetailStore implements IStore {
public void doPurchase() {
System.out.println("Doing purchase from Retail Store");
}
}
public class OnlineStore implements IStore {
public void doPurchase() {
System.out.println("Doing purchase from Online Store");
}
}
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/>
<!-- Store bean -->
<bean id="retailStore" class="com.theitroad.springproject.service.RetailStore" />
<!-- Store bean -->
<bean id="onlineStore" class="com.theitroad.springproject.service.OnlineStore" autowire-candidate="false" />
<!-- OrderServiceImpl bean with store bean dependency -->
<bean id="orderBean" class="com.theitroad.springproject.service.OrderServiceImpl" />
</beans>
在onlineStore的bean定义中,将autowire-candidate属性设置为false,以便将该bean排除在自动装配之外。
通过排除其中一个bean,可以避免NoUniqueBeanDefinitionException,如果有多个相同类型的bean,则抛出该异常。我们可以通过从onlineStore bean的定义中删除autowire-candidate =" false"进行检查。
Error creating bean with name 'orderBean' defined in class path resource [appcontext.xml]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.theitroad.springproject.service.IStore' available: expected single matching bean but found 2: retailStore,onlineStore
自动布线时还有其他解决冲突的方法,请检查使用@Autowired注释的Spring自动布线以了解如何使用@Primary和@Qualifier注释进行操作。

