Search code examples
javafactory-methodspring-ioc

How can I do parameterized dependency injection with Spring?


I was wondering how to solve the following problem using Spring dependency injection:

Given that I have a list of Transactions of different types, I'd need to process them based on their TransactionType. So I’d have a TransactionController with a TransactionService as such:

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);
}

Without using Spring IoC, I would use a Simple Factory pattern to return the implementation based on the Type enum:

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

How can I achieve the same injecting the TransactionService? I can't use the @Qualifier annotation, as implementation depends on the TransactionType. I've stumbled upon an article in the spring docs showing Instantiation using a factory method, but I cannot figure how to pass arguments to it.

I believe I probably have to use a different design with Spring IoC. I guess since I've always used the Simple Factory, Factory and Abstract Factory patterns, I can’t see a different way of solving this…

Can someone also please format this for me? The android app doesn't seem to do this, sorry!


Solution

  • In this case, factory pattern or similar is the correct solution, IMHO. Just implement a factory/registry/locator object and inject that using Spring. The rest is as usual. Injection happens when your object is created, but you need different implementations of the service during runtime. In this case, only service locator, factory or similar patterns make sense.