Kotlin 使用 Springboot 反射执行方法并自动传参

在使用反射的时候,执行方法的时候在想如果Springboot 能对需要执行的反射方法的参数自动注入就好了。所以就有了下文。

知识点

  • 获取上下文
  • 通过上下文获取 Bean
  • 通过上下文创建一个对象,该对象所需的参数由 Springboot 自己注入
  1. 创建参数

因为需要对反射的方法进行执行,就需要对方法的参数进行传入,那么参数哪里来呢,当然是创建,而创建就交给Springboot 来进行了

注意:Springboot 创建 Bean 需要你注入 ApplicationContext

kotlin 复制代码
// 调用这个方法可以获取 bean 如果没有则创建。并自动注册到 springboot 中

fun getOrCreateBean(applicationContext: ApplicationContext, clazz: Class<*>, isRegister: Boolean = true): Any {
   return kotlin.runCatching {
       applicationContext.getBean(clazz)
   }.getOrDefault(
       applicationContext.autowireCapableBeanFactory.createBean(clazz).apply {
           if (isRegister) registerBean(applicationContext, clazz, this)
       }
   )
}

private fun registerBean(applicationContext: ApplicationContext, clazz: Class<*>, bean: Any): Boolean {
   var isOK = false
   kotlin.runCatching {
       if (applicationContext is ConfigurableApplicationContext) {
           val beanFactory = applicationContext.beanFactory as DefaultListableBeanFactory
           if (!applicationContext.containsBean(clazz.simpleName)) {
               beanFactory.registerSingleton(clazz.simpleName, bean)
               isOK = true
           } else {
               if (!applicationContext.containsBean(clazz.name)) {
                   beanFactory.registerSingleton(clazz.name, bean)
                   isOK = true
               }
           }
       }
   }
   return isOK
}
  1. 反射调用方法
kotlin 复制代码
val method = clazz.methods.filter { it.name == "test" }.first()

val params = method.parameters.map {
    getOrCreateBean(applicationContext, it.type)
}.toTypedArray()

method.invoke(bean, *params)
  1. applicationContext

如果你不知道 applicationContext 如何注入可以看下面代码

kotlin 复制代码
@Autowired
lateinit var applicationContext:ApplicationContext
相关推荐
国思RDIF框架2 小时前
RDIFramework.NET CS 敏捷开发框架 V6.3 版本重磅发布!.NET8+Framework双引擎,性能升级全维度进化
后端·.net
心在飞扬2 小时前
ReRank重排序提升RAG系统效果
前端·后端
喝茶与编码2 小时前
Python异步并发控制:asyncio.gather 与 Semaphore 协同设计解析
后端·python
不早睡不改名2 小时前
网络编程基础:从BIO到NIO再到AIO(一)
后端
开源之眼2 小时前
《github star 加星 Taimili.com 艾米莉 》为什么Java里面,Service 层不直接返回 Result 对象?
java·后端·github
心在飞扬2 小时前
RAPTOR 递归文档树优化策略
前端·后端
zone77392 小时前
003:RAG 入门-LangChain 读取图片数据
后端·python·面试
心在飞扬2 小时前
LangChain Parent Document Retriever (父文档检索器)
后端
zone77392 小时前
002:RAG 入门-LangChain 读取文本
后端·算法·面试
用户8356290780512 小时前
在 PowerPoint 中用 Python 添加和定制形状的完整教程
后端·python