I have 2 tax implementation classes IndianTaxCalculation
and USTAxCalculation
which have implementaions for calculateTax()
method. I need to populate the class dynamically based on user login whether Indian or US, the respective Tax calculation method should call. How can i achieve this in Spring?
Asked
Active
Viewed 152 times
0

Andrey Korneyev
- 26,353
- 15
- 70
- 71

Srinivas
- 1
3 Answers
1
Try something like this:
@Autowired
@Qualifier("indian")
private TaxCalculation indianTax;
@Autowired
@Qualifier("us")
private TaxCalculation usTax;
public void calculateTaxes(Client client) {
if (client.isFromIndia()) {
indiaTax.calculate(client);
} else if (client.isFromUS()) {
usTax.calculate(client);
}
}

WeMakeSoftware
- 9,039
- 5
- 34
- 52
-
`@Bean` isn't used to inject a bean. It's used to declare one. What is needed is `@Autowired`, with `@Qualifier`. – JB Nizet Sep 26 '14 at 06:05
0
I think the topic below can answer your question. Please refer to How to do conditional auto-wiring in Spring?
0
You can create a locator service like:
public class ServiceLocator implements ApplicationContextAware
{
private static ApplicationContext context;
public void setApplicationContext(ApplicationContext context)
{
this.context = context;
}
public static <T> T getServiceBean(Class<T> serviceClass, String beanName)
{
return context.getBean(beanName, serviceClass);
}
}
And your service like:
public void calculateTaxes(Client client)
{
if (client.isFromIndia())
{
ServiceLocator.getServiceBean(TaxCalculation.class, "indiaTaxBeanName").calculate(client);
}
else if (client.isFromUS())
{
ServiceLocator.getServiceBean(TaxCalculation.class, "usTaxBeanName").calculate(client);
}
}

varun
- 684
- 1
- 11
- 30