带有Kotlin&Jackson反序列化的Spring:lateinit属性<attribute>尚未初始化

时间:2018-10-25 14:01:06

标签: spring spring-boot kotlin jackson

我必须承认我是Kotlin的新手,并且是Spring的新手,但是我必须使用那些工具,所以我在这里。

我有一个自定义的Jackson反序列化程序,它需要一个外部(Spring Boot属性文件)配置的类的实例才能完成其工作,但是尽管我尝试了,但始终会遇到以下错误:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is kotlin.UninitializedPropertyAccessException: lateinit property cordaRPC has not been initialized

由于伪自动Spring的东西,我真的不知道该如何进行……我认为可能杰克逊的检测发生在配置属性类之前,但是我将等待您的帮助。


为了提供一些背景信息,以下是一些原型作品:

错误源是cordaRPC中的DumpDataDeserializer.kt

文件:CordaGateway.kt:

@Component
@ConfigurationProperties(prefix = "corda.rpc")
class CordaGateway(@Value("\${$CORDA_NODE_HOST_ADDRESS}") private val host: String,
                   @Value("\${$CORDA_NODE_RPC_PORT}") private val port: Int,
                   @Value("\${$CORDA_NODE_RPC_USERNAME}") private val username: String,
                   @Value("\${$CORDA_NODE_RPC_PASSWORD}") private val password: String)
    : AutoCloseable
{
    lateinit var rpcConnection: CordaRPCConnection
    lateinit var proxy: CordaRPCOps

    private val logger = LoggerFactory.getLogger(CordaGateway::class.java)

    @PostConstruct
    fun initialiseNodeRPCConnection() {
        val rpcAddress = NetworkHostAndPort(host, port)
        val rpcClient = CordaRPCClient(rpcAddress)
        val rpcConnection = rpcClient.start(username, password)
        proxy = rpcConnection.proxy
    }

    @PreDestroy
    override fun close() {
        rpcConnection.notifyServerAndClose()
    }
}

文件:DumpData.kt:

// Untouchable external class
import net.corda.core.identity.Party

data class DumpData(val value: Int, val test: String, val user: Party)

文件:DumpDataDeserializer.kt

class DumpDataDeserializer(vc: Class<*>? = null) : StdDeserializer<DumpData>(vc) {

    private val logger = LoggerFactory.getLogger(TestController::class.java)

    @Autowired
    private lateinit var cordaRPC: CordaGateway

    override fun deserialize(jp: JsonParser, ctxt: DeserializationContext): DumpData {
        val node: JsonNode = jp.codec.readTree(jp)

        val value = node.get("value").intValue()
        val editedTest = node.get("test").textValue().plus(" edited!")
        val userName = node.get("user").textValue()

        val party = cordaRPC.proxy.wellKnownPartyFromX500Name(CordaX500Name.parse(userName))!!    

        return DumpData(value, editedTest, party)
    }
}

文件:CustomJsonConfig.kt:

@Configuration
class CustomJsonConfig {
    @Bean
    fun prova(): Module {
        return SimpleModule().addDeserializer(DumpData::class.java, DumpDataDeserializer())
    }
}

反序列化的调用方式如下:

val data = objMapper.treeToValue(body.get("prova"), DumpData::class.java)

谢谢!

0 个答案:

没有答案