0

Spring依存性注入を使用して次の問題を解決する方法を考えていました:

さまざまなタイプのリストがTransactionsあるので、それらに基づいてそれらを処理する必要がありますTransactionType。だから私はそのようなものを持っているでしょTransactionControllerTransactionService:

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 を使用しない場合は、Simple Factory パターンを使用して Type 列挙型に基づいて実装を返します。

public class TransactionServiceFactory {
    public TransactionService(TransactionType transactionType) {
        // switch case to return correct implementation.
    }
}

を注入して同じことを達成するにはどうすればよいTransactionServiceですか?@Qualifier実装はに依存するため、注釈を使用できませんTransactionType。ファクトリーメソッドを使用したインスタンス化を示す春のドキュメントの記事に出くわしましたが、それに引数を渡す方法がわかりません。

おそらく、Spring IoC では別の設計を使用する必要があると思います。私はいつも Simple Factory、Factory、Abstract Factory のパターンを使用してきたので、これを解決する別の方法が思い浮かびません…</p>

誰かが私のためにこれをフォーマットしてもらえますか? Android アプリはこれを行っていないようです。申し訳ありません。

4

2 に答える 2

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 に答える