private Object getOld(String tableName, Object id) {
String className = tableName.replaceAll("com.cloudMS.entity.", "") + "Mapper";
//springBoot自带的反射的方法名需要满足:className不是使用全类名例如:com.way.inter.impl.CalImpl,需要转换成类名首字母小写:calImpl。因为类交给spring管理的时候一般默认使用小写的类名作为bean的id;
String methodName = "selectByPrimaryKey";
//获取springBoot的上下文
ApplicationContext context = Application.applicationContext;
//通过上下文获取bean对象
Object clz = context.getBean(className);
//手动注入需要自动注入的对象,就是有@Autowire注解的bean(类,接口,等)
context.getAutowireCapableBeanFactory().autowireBean(clz);
//用springBoot专门的反射工具类获取指定的类方法
Method method = ReflectionUtils.findMethod(clz.getClass(), methodName, id.getClass());
//执行获取的bean的指定的方法
Object o = ReflectionUtils.invokeMethod(method, clz, id);
return o;
}
springBoot反射踩坑
最新推荐文章于 2025-05-20 20:26:19 发布