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
相关推荐
杨凯凡6 小时前
【021】反射与注解:Spring 里背后的影子
java·后端·spring
riNt PTIP6 小时前
SpringBoot创建动态定时任务的几种方式
java·spring boot·spring
Ares-Wang6 小时前
Flask》》 Flask-Bcrypt 哈希加密
后端·python·flask
alexhilton6 小时前
Compose中的CameraX二维码扫描器
android·kotlin·android jetpack
小码哥_常6 小时前
Spring Boot项目大变身:为何要拆成这六大模块?
后端
星晨羽8 小时前
西门子机床opc ua协议实现变量读写及NC文件上传下载
java·spring boot
yuweiade8 小时前
Spring Boot 整合 Redis 步骤详解
spring boot·redis·bootstrap
码事漫谈8 小时前
兵临城下:DeepSeek-V4 的技术突围与算力“成人礼”
后端
三水不滴9 小时前
SpringAI + SpringDoc + Knife4j 构建企业级智能问卷系统
经验分享·spring boot·笔记·后端·spring
2601_949814699 小时前
Docker部署Spring Boot + Vue项目
vue.js·spring boot·docker