java - Jackson StdDeserializer 的自定义实例中 Autowiring Bean

标签 java spring spring-boot jackson json-deserialization

我有一个请求对象,使用对象成员的自定义反序列化器

@JsonDeserialize(using = SomeClassDeserializer.class)
private SomeClass someClass;

默认情况下,Spring Boot 不会 Autowiring 带注释的字段,即使该类使用 @Component 进行注释,因为 Jackson 会处理实例化。如何保留 Jackson 所需的默认构造函数并注入(inject) bean 以在反序列化器中使用?

最佳答案

我发现答案在于第三个构造函数,它使用传统的 @Autowired 注释并以这种方式注入(inject)所需的 bean。但是,不要使用成员分配的典型实例,而是将该字段声明为静态并将此注入(inject)的 bean 分配给 Jackson 生成的反序列化器的所有实例。这是一种棘手的解决方法,但它为我解决了问题。

public class SomeClassDeserializer extends StdDeserializer<SomeObject> {
    private static SomeUtil someUtil;

    public SomeClassDeserializer(Class<?> vc) {
        super(vc);
    }

    public SomeClassDeserializer() {
        this(null);
    }

    @Autowired
    public SomeClassDeserializer(SomeUtil someUtil) {
        this(null);
        SomeClassDeserializer.someUtil= someUtil;
    }

关于java - Jackson StdDeserializer 的自定义实例中 Autowiring Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48890065/

相关文章:

java - 如何将数据保存在多个 sql 行的一个 thymeleaf 页面中

java - 数组索引越界项目欧拉问题 17

java - 在基于注释的 Spring Boot 应用程序中实现插件架构

spring - "The matching wildcard is strict, but no declaration can be found for element ' mvc :annotation-driven'?

java - 在我的带有 spring-boot 的项目中找不到@Autowired

java - 有效的正则表达式语句不是 Java 中的有效匹配

java - jsp 中的非法属性(违反 Sonar )

java - 404 错误配置与预编译的 jsp 不工作

java - 在 Spring Data Rest 中启用跨源请求

java - 使用 Java 泛型的 Hibernate 映射异常