手机网站建站多少钱,公众号做视频网站吗,四川做网站的公司有哪些,西安工程信息交易中心在使用反射的时候#xff0c;执行方法的时候在想如果Springboot 能对需要执行的反射方法的参数自动注入就好了。所以就有了下文。
知识点
获取上下文通过上下文获取 Bean通过上下文创建一个对象#xff0c;该对象所需的参数由 Springboot 自己注入
创建参数
因为需要对反…在使用反射的时候执行方法的时候在想如果Springboot 能对需要执行的反射方法的参数自动注入就好了。所以就有了下文。
知识点
获取上下文通过上下文获取 Bean通过上下文创建一个对象该对象所需的参数由 Springboot 自己注入
创建参数
因为需要对反射的方法进行执行就需要对方法的参数进行传入那么参数哪里来呢当然是创建而创建就交给Springboot 来进行了 注意Springboot 创建 Bean 需要你注入 ApplicationContext // 调用这个方法可以获取 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 falsekotlin.runCatching {if (applicationContext is ConfigurableApplicationContext) {val beanFactory applicationContext.beanFactory as DefaultListableBeanFactoryif (!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
}反射调用方法
val method clazz.methods.filter { it.name test }.first()val params method.parameters.map {getOrCreateBean(applicationContext, it.type)
}.toTypedArray()method.invoke(bean, *params)applicationContext
如果你不知道 applicationContext 如何注入可以看下面代码
Autowired
lateinit var applicationContext:ApplicationContext