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
相关推荐
MarkGosling1 小时前
【开源项目】网络诊断告别命令行!NetSonar:开源多协议网络诊断利器
运维·后端·自动化运维
congvee1 小时前
springboot 学习第1期 - 创建工程
spring boot
Codebee1 小时前
OneCode3.0 VFS分布式文件管理API速查手册
后端·架构·开源
_新一1 小时前
Go 调度器(二):一个线程的执行流程
后端
estarlee1 小时前
腾讯云轻量服务器创建镜像免费API接口教程
后端
风流 少年2 小时前
Cursor创建Spring Boot项目
java·spring boot·后端
毕设源码_钟学姐2 小时前
计算机毕业设计springboot宿舍管理信息系统 基于Spring Boot的高校宿舍管理平台设计与实现 Spring Boot框架下的宿舍管理系统开发
spring boot·后端·课程设计
军军君012 小时前
基于Springboot+UniApp+Ai实现模拟面试小工具二:后端项目搭建
前端·javascript·spring boot·spring·微信小程序·前端框架·集成学习
Wy. Lsy3 小时前
Kotlin基础学习记录
开发语言·学习·kotlin
方圆想当图灵3 小时前
ScheduledFutureTask 踩坑实录
后端