功能目的:传入类名、方法名和参数。动态执行Springboot的实现类方法
主要实现流程:获取SpringBoot创建好的工厂。
1.工具类:ApplicationContextUtils
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
//用于获取SpringBoot创建好的工厂
//交给Spring管理
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
//将创建好的工厂以参数形式传递给你
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
//提供在工厂中获取对象的方法
public Object getBean(String beanName){
return applicationContext.getBean(beanName);
}
}2.测试方法
@Resource
private ApplicationContextUtils applicationContextUtils;
try {
//定义入参类型
Class[] argsType = new Class[]{Class.forName("java.lang.Long")};
//定义入参参数
Object[] args = new Object[]{stationId};
//从Spring工厂获取类的实例
Object owner=applicationContextUtils.getBean("实现类的Service");
//调用哪个方法
String methodName="实现类的方法名称";
Class ownerClass = owner.getClass();
Method method = ownerClass.getMethod(methodName, argsType);
Object objRtn = method.invoke(owner, args);
System.out.println(objRtn);
} catch (Exception e) {
e.printStackTrace();
}
本文为程序员之家原创文章,转载无需和我联系,但请注明来自程序员之家www.baldhome.cn
