我想知道如何使用 Spring 依赖注入解决以下问题:
鉴于我有一个Transactions
不同类型的列表,我需要根据它们的TransactionType
. 所以我有一个TransactionController
这样的TransactionService
:
public class TransactionController {
private TransactionService transactionService;
public void doStuff(List<Transaction> transactions) {
for (Transaction transaction : transactions) {
// use the correct implementation of transactionService based on the type
transactionService.process(transaction);
}
}
}
public interface TransactionService {
void process(transaction);
}
在不使用 Spring IoC 的情况下,我将使用简单工厂模式来返回基于 Type 枚举的实现:
public class TransactionServiceFactory {
public TransactionService(TransactionType transactionType) {
// switch case to return correct implementation.
}
}
我怎样才能实现相同的注入TransactionService
?我不能使用@Qualifier
注释,因为实现取决于TransactionType
. 我偶然发现 spring 文档中的一篇文章显示了使用工厂方法进行实例化,但我不知道如何将参数传递给它。
我相信我可能不得不对 Spring IoC 使用不同的设计。我想因为我一直使用简单工厂、工厂和抽象工厂模式,我看不出有什么不同的方法来解决这个问题……</p>
有人也可以为我格式化吗?android 应用程序似乎没有这样做,对不起!