2016-03-03 41 views
1

我有一个pojo类,其中我必须根据输入字符串调用多个ejbs。例如,如果输入是x,我必须调用XServiceBean,如果它是Y,则必须调用YServiceBean。 我打算参数化输入字符串x和数据库或XML中相应的服务bean。我不想将多个条件或切换案例放在基于输入字符串的服务bean上。需要根据输入字符串调用多个EJB

是否有任何简单的模式,我可以用来实现这一点。将是有益的,如果你能举一些例子 谢谢

回答

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

服务工厂返回要调用

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"); 
    } 
} 
+0

非常感谢乌尔建议。 – Sudersan