2

I'm new to spring and I'm trying to refactor some code, I have the following "Session.class":

public class Session {
    ...
    private Wallet currenetWallet;
    ...
    public Session(..., int sessionId, ...) {
        ...

        ThirdPartyToken token = context.getBean(ThirdPartyTokenDAO.class).getThirdPartyToken(sessionId);

        if (token.getExternalUser().getMerchant().getType().equals("SOAPMerchant")) {
            currenetWallet = (Wallet) context.getBean("SOAPExternalWallet", token);
        }
        else if (token.getExternalUser().getMerchant().getType().equals("JSONMerchant")) {
            currenetWallet = (Wallet) context.getBean("JSONExternalWallet", token);
        }
        else {
            currenetWallet = (Wallet) context.getBean("GuestWallet", 1000.0);
        }

        ...
    }   
}

I read that using context.getBean() is a bad practice, and makes the class untestable. What would be the correct way of wiring the currentWallet according to the above?

Yuval Barness
  • 80
  • 1
  • 8
  • Inject the three values, and choose which one to use based on the merchant type – JB Nizet Jul 11 '17 at 08:16
  • Today I have 3, but what if tomorrow I'll have a dozen types, wouldn't it be a waste to wire them all ? Although I do like this solution, it will be the easiest to implement – Yuval Barness Jul 11 '17 at 08:20
  • You actually depend on `Wallet` class, not on `sessionId`, so this is what you should be wiring and expecting in constructor. Depending on how rest of system defined, you can have a `Wallet` prototype bean, creation of which depends on `Token`, which in turn depends on that sessionId. – M. Prokhorov Jul 11 '17 at 08:35

1 Answers1

0

Create an interface Wallet and create implementation classes like SOAPExternalWallet, JSONExternalWallet, GuestWallet.
Create a factory class and then based on the type return the right implementation from factory class.

pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • But then I don't use spring, I'd like the currentWallet field to be @autowired somehow... – Yuval Barness Jul 11 '17 at 08:25
  • 1
    see my answer here https://stackoverflow.com/questions/44000672/spring-how-to-change-interface-implementations-at-runtime/44001051#44001051 – pvpkiran Jul 11 '17 at 08:26