如何仅使用应用程序中的配置来解决此问题
语境?
你可以使用qualifier
如下所示的标签(参见https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-autowired-annotation-qualifiers https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-autowired-annotation-qualifiers)
<context:annotation-config/>
<beans>
<bean class="your_pkg_route.Vehicle">
<qualifier value="bike"/>
</bean>
</beans>
</context:annotation-config>
我发现人们在谈论 bean 中的 autowire 属性
声明,我需要更多解释
使用注释
@Autowired https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html用于 bean 声明方法会通过(另一个)声明的 bean 注入定义的依赖项。现在,如果您的依赖项位于应用程序的同一上下文中,则无需使用@Autowired
根本不需要注释,因为 Spring 能够自己找出它们。因此,如果您的依赖项位于应用程序上下文之外,那么您可以使用它。
例如,参考以下代码:
@Autowired
@Bean
public MyBean getMybean(Dependency1 depdency1, Dependency2 depdency2) {
return new MyBean(depdency1.getSomeStuff(), depdency2.getSomeOtherStuff());
}
Here, @Autowired
会找到一个实例Dependency1
and Dependency2
并将提供它们来创建一个实例MyBean
.
使用xml配置
From 专业春季5 https://www.apress.com/gp/book/9781484228074... Spring 支持五种自动装配模式。
-
byName
:使用时byName
自动装配,Spring 尝试将每个属性连接到同名的 bean。因此,如果目标 bean 有一个名为foo
and a foo
豆定义在ApplicationContext
, the foo
豆被分配给foo
目标的属性。
-
byType
:使用时byType
自动装配,Spring 尝试连接每个
通过自动使用相同类型的 bean 来实现目标 bean 的属性ApplicationContext
.
-
constructor
: 这个功能就像byType
接线,不同之处在于它使用构造函数而不是设置器来执行注入。 Spring 尝试在构造函数中匹配最大数量的参数。因此,如果您的 bean 有两个构造函数,其中一个接受String
和一个接受String
and an Integer
,并且您同时拥有String
and an Integer
豆子在你的ApplicationContext
,Spring使用双参数构造函数。
-
default
: Spring 将在以下之间进行选择constructor
and byType
模式
自动地。如果您的 bean 有一个默认(无参数)构造函数,Spring 使用byType
;否则,它使用构造函数。
-
no
: 这是默认的
所以,在你的情况下,你需要做这样的事情(但是,我不会推荐它。为什么?,你需要声明Vehicle
类作为一个 bean 和一个组件这是不正确的,请参阅Spring:@Component 与 @Bean https://stackoverflow.com/questions/10604298/spring-component-versus-bean。另一方面,我不确定你是否可以使用它,只是将其声明为 bean):
// xml config
<context:annotation-config/>
<beans>
// use the primary tag here too! in order to say this the primary bean
// this only works when there are only two implementations of the same interface
<bean id="bike" primary="true" class="your_pkg_route.Bike"/>
<bean id="car" class="your_pkg_route.Car"/>
<bean autowire="byName" class="your_pkg_route.VehicleService"/>
<beans>
</context:annotation-config>
// VehicleService
@Component
public class VehicleService {
private Vehicle bike; // call attribute 'bike' so it is autowired by its name
public void service() {
//...
}
}
正如您所看到的,尝试使用 xml 配置执行此操作会遇到很多复杂情况,因此我建议您如果可能的话使用注释选项。
相关文章:
- 为什么 Spring 配置类中的 @Bean 方法不需要 @Autowired? https://stackoverflow.com/questions/32078600/why-do-i-not-need-autowired-on-bean-methods-in-a-spring-configuration-class
- @Bean 和 @Autowired 之间的区别 https://stackoverflow.com/questions/34172888/difference-between-bean-and-autowired
PS:我还没有测试任何发布的代码。