需要根据输入字符串调用多个EJB

Need to call multiple EJBs based on the input string

我有一个 pojo class,其中我必须根据输入字符串调用多个 ejb。例如,如果输入是 x,我必须调用 XServiceBean,如果是 Y,我必须调用 YServiceBean。 我计划在数据库或 xml 中参数化输入字符串 x 和相应的服务 bean。我不想放置多个 if 条件或 switch case 来根据输入字符串调用服务 bean。

有没有什么简单的模式可以用来实现这个。如果你能举一些例子会很有帮助 谢谢

Main class 您可以在其中 运行 作为 java 进行测试

package stack;

public class ServiceInit
{

   public static void main(String[] args)
   {
       new ServiceInit();
   }

   public ServiceInit()
   {
       ServiceBeanInterface xbean = ServiceFactory.getInstance().getServiceBean("X");

       xbean.callService();

       ServiceBeanInterface ybean = ServiceFactory.getInstance().getServiceBean("Y");

       ybean.callService();
   }
}

returns 您要调用的 bean 的服务工厂

package stack;

public class ServiceFactory
{

/*
 * you can do it with factory and class reflection if the input is always the prefix for the service bean. 
 */
private static ServiceFactory instance;

// the package name where your service beans are
private final String serviceBeanPackage = "stack.";

private ServiceFactory()
{

}

public static ServiceFactory getInstance()
{
    if (instance == null)
    {
        instance = new ServiceFactory();
    }
    return instance;
}

@SuppressWarnings("unchecked")
public ServiceBeanInterface getServiceBean(String prefix)
{
    ServiceBeanInterface serviceBean = null;
    try
    {

        Class<ServiceBeanInterface> bean = (Class<ServiceBeanInterface>) Class
                .forName(serviceBeanPackage + prefix + "ServiceBean");

        serviceBean = bean.newInstance();
    }
    catch (ClassNotFoundException | InstantiationException | IllegalAccessException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return serviceBean;

}

}

你的服务实现的接口classes

package stack;

public interface ServiceBeanInterface
{
    void callService();
}

XServiceBean class

package stack;

public class XServiceBean implements ServiceBeanInterface
{

@Override
public void callService()
{
    System.out.println("I am X");
}

}

YServiceBean class

package stack;

public class YServiceBean implements ServiceBeanInterface
{

   @Override
   public void callService()
   {
       System.out.println("I am Y");
   }
}