Dynamic injection in Spring

后端 未结 3 784
予麋鹿
予麋鹿 2021-01-29 05:00

I have 2 tax implementation classes IndianTaxCalculation and USTAxCalculation which have implementaions for calculateTax() method. I need

3条回答
  •  醉话见心
    2021-01-29 05:24

    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 getServiceBean(Class 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);
     }
    

    }

提交回复
热议问题