0

我想知道如何使用 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 应用程序似乎没有这样做,对不起!

4

2 回答 2

2

在这种情况下,工厂模式或类似模式是正确的解决方案,恕我直言。只需实现一个工厂/注册表/定位器对象并使用 Spring注入它。其余的和往常一样。注入发生在创建对象时,但在运行时需要不同的服务实现。在这种情况下,只有服务定位器、工厂或类似模式才有意义。

于 2014-09-11T19:02:35.770 回答
1

在这种情况下,您可以使用 Map 属性注入:

**private Map<TransactionServiceMap>  transactionServiceMap;**


<!-- results in a transactionServiceMap(java.util.Map) call -->
**<property name="transactionServiceMap">
    <map>
        <entry key="TRANSACTION_TYPE_1" value-ref="transactionService1"/>
        <entry key ="TRANSACTION_TYPE_2" value-ref="transactionService2"/>
    </map>
</property>**

并修改 for 循环,如下所述:

public void doStuff(List transactions) {

        for (Transaction transaction : transactions) {

            // use the correct implementation of transactionService based on the type

            TransactionService transactionService = transactionServiceMap
                                          .get(transaction.getType());

            transactionService.process(transaction);



        }

    }
于 2014-09-11T19:19:33.840 回答