2016-03-03 25 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

相關問題