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
相关推荐
六月的雨在掘金4 分钟前
狼人杀法官版,EdgeOne 带你轻松上手狼人杀
前端·后端
绝无仅有10 分钟前
使用 Docker、Jenkins、Harbor 和 GitLab 构建 CI/CD 流水线
后端·面试·github
张同学的IT技术日记20 分钟前
必看!用示例代码学 C++ 继承,快速掌握基础知识,高效提升编程能力
后端
杨杨杨大侠21 分钟前
10 - 性能优化和扩展 🚀
后端·开源·workflow
叫我阿柒啊24 分钟前
Java全栈开发实战:从Spring Boot到Vue3的项目实践
java·spring boot·微服务·性能优化·vue3·全栈开发
前端老鹰25 分钟前
Node.js 网页解析神器:cheerio 模块实战指南,像 jQuery 一样玩转 HTML
后端·node.js
小明说Java36 分钟前
基于 Spring Boot 与 AES 实现接口响应数据加密
后端
猿java38 分钟前
在 Spring中,用id和name命名Bean,究竟有什么区别?
后端·spring·架构
猿java40 分钟前
OAuth2是什么?它有哪些授权模式?
后端·安全·架构