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

时间:2016-03-03 10:49:58

标签: java design-patterns ejb-3.1

我有一个pojo类,我必须根据输入字符串调用多个ejbs。例如,如果输入是x,我必须调用XServiceBean,如果是Y,我必须调用YServiceBean。 我打算在数据库或xml中参数化输入字符串x和相应的服务bean。我不想放置多个if条件或切换案例来根据输入字符串调用服务bean。

我可以使用任何简单的模式来实现这一目标。如果你能给出一些例子,将会很有帮助 谢谢

1 个答案:

答案 0 :(得分:1)

可以作为测试目的运行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();
   }
}

Service Factory,它返回您要调用的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;

}

}

由服务类实现的接口

package stack;

public interface ServiceBeanInterface
{
    void callService();
}

XServiceBean类

package stack;

public class XServiceBean implements ServiceBeanInterface
{

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

}

YServiceBean类

package stack;

public class YServiceBean implements ServiceBeanInterface
{

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