gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:33:11 24 4
gpt4 key购买 nike

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

是否有任何简单的模式可以用来实现这一目标。如果你能举一些例子会有帮助谢谢

最佳答案

可以作为 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();
}
}

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

}

}

由您的服务类实现的接口(interface)

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

关于java - 需要根据输入字符串调用多个EJB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35770075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com