在 Spring 中将多个实现注入单个服务 [英] Injecting multiple implementations to a single service in Spring

查看:25
本文介绍了在 Spring 中将多个实现注入单个服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 DataSource 的服务接口和 1 个以上的实现,例如 XMLDataSourceDataBaseDataSource 等.

I have a servive interface called DataSource and more than 1 implementations like XMLDataSource, DataBaseDataSource etc.

我想根据一些用户交互向我的 Struts2 Action 注入(Spring)适当的实现,比如如果用户点击 XML 那么我需要使用 XML 实现.Spring已经用于DI框架.

I want to inject(Spring) appropriate implementation to my Struts2 Action based on some user interaction like if User clicks on XML then I need to use XML implementation. Spring has been used for DI framework.

@Autowired
private DataSource dataSource;

请提出实现这一目标的最佳方法.

Please suggest what is best way to achieve this.

推荐答案

当使用 @Autowired 注释时,它是按类型自动装配的,您应该切换到按名称自动装配,这可以使用 @Qualifier 注释

When using the @Autowired annotation it's autowiring by type, you should switch to autowiring by name which can be done using the @Qualifier annotation

@Autowired
@Qualifier("yourDataSource")
private DataSource dataSource;

这篇关于在 Spring 中将多个实现注入单个服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆