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
相关推荐
Mr.4567几秒前
Spring Boot 3 + EasyExcel 3.x 实战:构建高效、可靠的Excel导入导出服务
spring boot·后端·excel
匆匆忙忙之间游刃有余1 分钟前
Openclaw 为什么突然火了?我拆完它的架构后,发现它正在把 AI 助手变成“数字分身”
人工智能·后端
悟空码字5 分钟前
别再让你的SpringBoot包"虚胖"了!这份瘦身攻略请收好
java·spring boot·后端
掘金者阿豪6 分钟前
MiGPT GUI给小爱音箱装「AI 大脑」,自定义人设 + 百变音色!cpolar 内网穿透实验室第 726 个成功挑战
前端·后端
盐水冰16 分钟前
【烘焙坊项目】后端搭建(13)- 数据统计--图形报表
java·后端·学习·spring
野犬寒鸦17 分钟前
从零起步学习计算机操作系统:I/O篇
服务器·开发语言·网络·后端·面试
后端不背锅18 分钟前
分布式事务解决方案:2PC、3PC、TCC、Saga
后端
二闹20 分钟前
Python中@classmethod和@staticmethod的真正区别懂了吗?
后端·python
法欧特斯卡雷特39 分钟前
Kotlin 2.3.20 现已发布,来看看!
android·前端·后端