动态调用service层服务方法处理

----- ApplicationContextUtils.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;

public void setApplicationContext(ApplicationContext applicationContext) {

ApplicationContextUtils.applicationContext = applicationContext;
}

public static Object getBean(String name) {
return applicationContext.getBean(name);
}

public static Object getBean(Class<?> c) {
return applicationContext.getBean(c);
}


}
----- TestEnum.java 
/**
* @Author
* @Date 2021/5/18
* @Version 1.0
*
* 参数类型 与 操作方法名 枚举
*/
public enum TestEnum {

FDINFO(BusiConstants.PARAMS_TP.FDINFO,"fundInfoService","rwFdInfoApply",FdInfoService.class);

private String bizParamTp;
private String serviceBeanName;
private String methodName;
private Class<?> clazz;


ParamsTpMethodEnum(String bizParamTp, String serviceBeanName, String methodName,Class<?> clazz) {
this.bizParamTp = bizParamTp;
this.serviceBeanName = serviceBeanName;
this.methodName = methodName;
}

public String getBizParamTp() {
return bizParamTp;
}

public String getServiceBeanName() {
return serviceBeanName;
}

public String getMethodName() {
return methodName;
}

  public Class<?> getClazz(){
    return clazz;  
  }

public static ParamsTpMethodEnum getMethodNameByTp(String bizParamTp){
for (ParamsTpMethodEnum en : ParamsTpMethodEnum.values()) {
if(bizParamTp.equals(en.getBizParamTp())){
return en;
}
}
return null;
}
}

----- Service - TestServiceImpl.java

import org.springframework.util.ReflectionUtils;


public String invokeMethod(String aNo, Map<String, Object> rewData, String userId, String ap, String reMsg,TestEnum em) {
    try {
Method method = ReflectionUtils.findMethod(em.getClazz(), em.getMethodName(), null);
Object obj = ApplicationContextUtils.getBean(em.getServiceBeanName());
return (String) ReflectionUtils.invokeMethod(method, obj, aNo, rewData, userId, ap, reMsg);
} catch (Exception e) {
e.printStackTrace();
throw new FeiTianException("调用服务接口失败");
}
}
posted @ 2021-05-19 17:56  Mr_Precious  阅读(574)  评论(0编辑  收藏  举报