gpt4 book ai didi

spring - 在运行时生成的类中使用 Kotlin 对象

转载 作者:行者123 更新时间:2023-12-02 12:55:10 26 4
gpt4 key购买 nike

我正在使用 ByteBuddy 重新设置另一个库的类,以便向其中添加 Spring 依赖注入(inject)。问题是我无法实例化用作拦截器的类,这意味着我无法使用 Spring 注入(inject) ApplicationContext进入拦截器。

为了解决这个问题,我创建了一个对象 StaticAppContext ,得到 ApplicationContext通过实现 ApplicationContextAware 注入(inject):

@Component
object StaticAppContext : ApplicationContextAware {
private val LOGGER = getLogger(StaticAppContext::class)

@Volatile @JvmStatic lateinit var context: ApplicationContext

override fun setApplicationContext(applicationContext: ApplicationContext?) {
context = applicationContext!!
LOGGER.info("ApplicationContext injected")
}
}

这注入(inject)得很好(我可以看到日志消息),但是当我尝试访问 ApplicationContext从拦截器,我得到 kotlin.UninitializedPropertyAccessException: lateinit property context has not been initialized .

重新定义类和 incerceptor 的类在此类中定义:
package nu.peg.discord.d4j

import net.bytebuddy.ByteBuddy
import net.bytebuddy.dynamic.ClassFileLocator
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy
import net.bytebuddy.implementation.MethodDelegation
import net.bytebuddy.implementation.SuperMethodCall
import net.bytebuddy.implementation.bind.annotation.*
import net.bytebuddy.matcher.ElementMatchers
import net.bytebuddy.pool.TypePool
import nu.peg.discord.config.BeanNameRegistry.STATIC_APP_CONTEXT
import nu.peg.discord.config.StaticAppContext
import nu.peg.discord.util.getLogger
import org.springframework.beans.BeansException
import org.springframework.beans.factory.config.AutowireCapableBeanFactory
import org.springframework.context.annotation.DependsOn
import org.springframework.stereotype.Component
import sx.blah.discord.api.IDiscordClient
import sx.blah.discord.modules.Configuration
import sx.blah.discord.modules.IModule
import sx.blah.discord.modules.ModuleLoader
import java.lang.reflect.Constructor
import java.util.ArrayList
import javax.annotation.PostConstruct

/**
* TODO Short summary
*
* @author Joel Messerli @15.02.2017
*/
@Component @DependsOn(STATIC_APP_CONTEXT)
class D4JModuleLoaderReplacer : IModule {
companion object {
private val LOGGER = getLogger(D4JModuleLoaderReplacer::class)
}

@PostConstruct
fun replaceModuleLoader() {
val pool = TypePool.Default.ofClassPath()

ByteBuddy().rebase<Any>(
pool.describe("sx.blah.discord.modules.ModuleLoader").resolve(), ClassFileLocator.ForClassLoader.ofClassPath()
).constructor(
ElementMatchers.any()
).intercept(
SuperMethodCall.INSTANCE.andThen(MethodDelegation.to(pool.describe("nu.peg.discord.d4j.SpringInjectingModuleLoaderInterceptor").resolve()))
).make().load(ClassLoader.getSystemClassLoader(), ClassLoadingStrategy.Default.INJECTION)

LOGGER.info("The D4J ModuleLoader has been replaced with ByteBuddy to allow for Spring injection")
}

override fun getName() = "Spring Injecting Module Loader"
override fun enable(client: IDiscordClient?) = true
override fun getVersion() = "1.0.0"
override fun getMinimumDiscord4JVersion() = "1.7"
override fun getAuthor() = "Joel Messerli <hi.github@peg.nu>"
override fun disable() {}
}

class SpringInjectingModuleLoaderInterceptor {
companion object {
private val LOGGER = getLogger(SpringInjectingModuleLoaderInterceptor::class)

@Suppress("UNCHECKED_CAST")
@JvmStatic
fun <T> intercept(
@This loader: ModuleLoader,
@Origin ctor: Constructor<T>,
@Argument(0) discordClient: IDiscordClient?,

@FieldValue("modules") modules: List<Class<out IModule>>,
@FieldValue("loadedModules") loadedModules: MutableList<IModule>
) {
LOGGER.debug("Intercepting $ctor")
val loaderClass = loader.javaClass
val clientField = loaderClass.getDeclaredField("client")
clientField.isAccessible = true
clientField.set(loader, discordClient)

val canModuleLoadMethod = loaderClass.getDeclaredMethod("canModuleLoad", IModule::class.java)
canModuleLoadMethod.isAccessible = true

val factory = StaticAppContext.context.autowireCapableBeanFactory
for (moduleClass in modules) {
try {
val wired = factory.autowire(moduleClass, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false) as IModule
LOGGER.info("Loading autowired module {}@{} by {}", wired.name, wired.version, wired.author)
if (canModuleLoadMethod.invoke(loader, wired) as Boolean) {
loadedModules.add(wired)
} else {
LOGGER.info("${wired.name} needs at least version ${wired.minimumDiscord4JVersion} to be loaded (skipped)")
}
} catch (e: BeansException) {
LOGGER.info("Spring could not create bean", e)
}
}

if (Configuration.AUTOMATICALLY_ENABLE_MODULES) { // Handles module load order and loads the modules
val toLoad = ArrayList<IModule>(loadedModules)

val loadModuleMethod = loaderClass.getDeclaredMethod("loadModule", IModule::class.java)
while (toLoad.size > 0) {
toLoad.filter { loadModuleMethod.invoke(loader, it) as Boolean }.forEach { toLoad.remove(it) }
}
}
LOGGER.info("Module loading complete")
}
}
}

当我调试它时,IntelliJ 显示当拦截器尝试访问 StaticAppContext 时创建了一个新的 StaticAppContext 实例。 ,这是有道理的,因为抛出了异常。

从生成的代码调用时,Kotlin 对象不是真正的单例,还是我做错了什么?有什么办法可以解决这个问题?

该项目也可以在 Github 上找到: https://github.com/jmesserli/discord-bernbot/tree/master/src/main/kotlin/nu/peg/discord

编辑
我能够通过删除 spring-boot-devtools 来解决问题其中添加自己的 ClassLoader .当我尝试使用 Thread.currentThread().contextClassLoader 的建议时,我得到一个不同的异常,告诉我它已经被另一个 ClassLoader 加载了。 (这证实这是 ClassLoader s 的问题)。此外,似乎可能存在比赛的假设是正确的。

我现在有一个不同的问题,我会做一些研究,看看我是否可以自己解决。

最佳答案

一个 Kotlin object编译成如下布局:

public final class StaticAppContext {
public static final StaticAppContext INSTANCE;
private StaticAppContext();
static {}
}

该类隐含地是一个单例。因此,我想知道问题是否是类加载中的竞赛。很有可能已经调用了静态初始化程序。您确定您收到正确的日志消息吗?

关于spring - 在运行时生成的类中使用 Kotlin 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42333069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com