我想实现一个具有3个服务的spring boot应用程序。现在,我想按顺序从控制器运行3个服务。我想通过控制器传递服务和方法的名称以及输入参数和序列,并希望获得每个服务的结果。请让我知道如何通过一个简单的spring boot应用程序来实现这些目标。
答案 0 :(得分:0)
非常高水平的例子。通常需要使用“反射”来通过名称和/或调用方法动态创建类实例,而无需使用“ if”。请注意,如果您的“服务”是spring bean,则代码可能会有所不同。
interface Service {
void method();
}
class Service1 implements Service {
@Override
public void method() {
// do magic
}
}
class Service2 implements Service {
@Override
public void method() {
// do magic
}
}
class Test {
public void executeMe(String className, String methodName) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
// you may need to have full class name with package
Service service = (Service) Class.forName(className).newInstance();
if ("method".equalsIgnoreCase(methodName)) {
service.method();
}
}
}
更新
class Service1 {
public void method1() {
// do magic
}
public void method2() {
// do magic
}
}
class Service2 {
public void method3() {
// do magic
}
}
class Test {
public void executeMe(String className, String methodName) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
// you may need to have full class name with package
Service1 service = (Service1) Class.forName(className).newInstance();
if ("method1".equalsIgnoreCase(methodName)) {
service.method1();
}
}
}
使用Spring
class Test {
@Autowired
private Service1 service1;
@Autowired
private Service2 service2;
public void executeMe(String className, String methodName) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Map<String, Object> map = new HashMap<>();
map.put("service1", service1);
map.put("service2", service2);
// you may need to have full class name with package
if ("service1".equalsIgnoreCase(className)) {
Service1 service1 = (Service1) map.get(className);
if ("method1".equalsIgnoreCase(methodName)) {
service1.method1();
}
}
}
}
同样,这是非常高级的元代码。