Jackson `InvalidDefinitionException` с нативным изображением GraAlvm:« Невозможно построить экземпляр ... без делегат илJAVA

Программисты JAVA общаются здесь
Anonymous
Jackson `InvalidDefinitionException` с нативным изображением GraAlvm:« Невозможно построить экземпляр ... без делегат ил

Сообщение Anonymous »

Я создаю нативное изображение Graalvm для проекта Quarkus/Java 21 и сталкиваюсь с проблемами детериализации Джексона, которые хорошо работают на JVM.com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Cannot construct instance of `com.example.config.models.Configuration`:
cannot deserialize from Object value (no delegate- or property-based Creator):
this appears to be a native image, in which case you may need to configure reflection
at [Source: (ByteArrayInputStream); line: 1, column: 1]
< /code>
Full Stack Trace Adherpt: < /p>
com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition
com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition
com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator
com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault
com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject
com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize
com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue
com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose
com.fasterxml.jackson.databind.ObjectMapper.readValue
com.example.config.ConfigurationLoader.loadConfigurationFromYaml
com.example.config.HttpConfigurationLoader.loadConfiguration
com.example.config.AppProps.initialize
...


Что я попробовал

[*] Добавлено Refert-config.json в разделе SRC/Main/Resources/Meta-inf/Native-Image/ с такими жеребьями:

[
{
"name":"com.example.config.models.Configuration",
"allDeclaredFields":true,
"queryAllDeclaredMethods":true,
"queryAllDeclaredConstructors":true,
"methods":[{"name":"","parameterTypes":["java.util.Map"] }]
},
{
"name":"com.example.config.models.Configuration$Destination",
"allDeclaredFields":true,
"queryAllDeclaredMethods":true,
"queryAllDeclaredConstructors":true,
"methods":[{"name":"","parameterTypes":["java.lang.String","java.lang.String","int","java.lang.String","java.lang.String","java.lang.String","int","int","int","int"] }]
},
{
"name":"com.example.config.models.Configuration$Environment",
"allDeclaredFields":true,
"queryAllDeclaredMethods":true,
"queryAllDeclaredConstructors":true,
"methods":[{"name":"","parameterTypes":["com.example.config.models.Configuration$Destination"] }]
},
{
"name":"com.example.config.HttpConfigurationLoader",
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allDeclaredFields": true
},
{
"name": "com.fasterxml.jackson.annotation.JsonCreator"
}
]



[*] Проверенная структура JSON действительна и размещена в соответствии с Meta-INF/Native-Image .
[*] Пробовал зарегистрировать модуль Jackson через Meta-inf/services/com.fasterxml.jackson.databind.module InvalidDefinitionException < /code>. < /Li>
< /ul>

Вопрос < /h3>
Поскольку конфигурация и связанные с ними классы происходят из сторонней зависимости (я не могу изменить их, чтобы добавить аннотации или конструкторы), как я могу создать Jackson + GraAlvm (я не могу изменить их, чтобы добавить аннотации или конструкторы), как я могу создать джеральс-изображение. /> Есть ли способ автоматически создавать конфигурацию отражения для классов зависимостей, используемых Джексоном? Я сгенерировал автоматическое сгенерирование Refert-config.json и других через режим агента и поместил их в SRC \ Main \ Resources \ Meta-Image \
мне нужно создать свой собственный миксин или пользовательский десериализатор? Изображения?// Dummy dependency-like classes (cannot modify these)
package com.example.dep.config.models;

import java.util.Map;

public class Configuration {
private Map bootstrapConfig;

public Map getBootstrapConfig() { return bootstrapConfig; }
public void setBootstrapConfig(Map bootstrapConfig) { this.bootstrapConfig = bootstrapConfig; }

public static class Environment {
private Destination destination;
public Destination getDestination() { return destination; }
public void setDestination(Destination destination) { this.destination = destination; }
}

public static class Destination {
private String protocol;
private String host;
private int port;

public String getProtocol() { return protocol; }
public void setProtocol(String protocol) { this.protocol = protocol; }

public String getHost() { return host; }
public void setHost(String host) { this.host = host; }

public int getPort() { return port; }
public void setPort(int port) { this.port = port; }
}
}
< /code>
// Loader that uses Jackson to read YAML
package com.example.dep.config;

import com.example.dep.config.models.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import java.io.IOException;
import java.io.InputStream;

public class ConfigurationLoader {
private static final ObjectMapper MAPPER = new ObjectMapper(new YAMLFactory());

public Configuration loadConfiguration(String environment) throws IOException {
try (InputStream fileStream = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("config.yaml")) {
return MAPPER.readValue(fileStream, Configuration.class);
}
}
}
< /code>
// Utility class similar to AppProps in dependency lib
package com.example.dep.config;

import com.example.dep.config.models.Configuration;
import lombok.experimental.UtilityClass;

@UtilityClass
public class AppProps {

private static Configuration configuration;
private static Configuration.Destination currentDestination;
private static ConfigurationLoader loader;

public static void initialize() throws IOException {
loader = new ConfigurationLoader();
configuration = loader.loadConfiguration("dev"); // environment dummy
}

public static Configuration getConfiguration() {
return configuration;
}

public static Configuration.Destination getCurrentDestination() {
currentDestination = configuration.getBootstrapConfig().get("dev").getDestination();
return currentDestination;
}
}


Подробнее здесь: https://stackoverflow.com/questions/797 ... t-construc

Вернуться в «JAVA»