【问题标题】:Solve the circular dependencies error with Jackson, without using annotations用 Jackson 解决循环依赖错误,不使用注解
【发布时间】:2014-03-20 17:21:29
【问题描述】:

目前,我正在使用 Spring 框架编写一些 webapp。对于所有 @RestController API,我使用 Jackson 来生成 Json 对象。

@RestController 看起来像

@RestController
@RequestMapping("/api")
public class SomeAPI {
    @RequestMapping(method = RequestMethod.GET)
    public A getA() {
        A a = new A();
        return a;
    }
}

但是当两个对象具有双向引用时,就会出现循环依赖问题。例如,有两个 POJO 类如下:

class A {
    private B b;

    // constructor
    ...
    // setters and getters.
    ...
}


class B {
    private A a;

    // constructor
    ...
    // setters and getters.
    ...
}

我可以通过这种方式轻松解决它,使用注释:http://java.dzone.com/articles/circular-dependencies-jackson

但这不是我的意思。

现在,我无法更改 A 类和 B 类的代码,因此我无法在其中使用任何注释。 那不使用注解怎么解决这个问题呢?

提前感谢您的任何建议!

【问题讨论】:

  • 你能告诉我们你的控制器处理方法吗?你只是使用@ResponseBody吗?
  • @hsotirios-delimanolis 感谢您的回复。我只是简单地使用@ResponseBody作为返回值,仅此而已。
  • @Fify 如果您使用 xml 配置,然后尝试将 default-lazy-init="true" 添加到 bean 并查看它是否有效..
  • @Rembo 可以更详细地向我解释为什么这应该解决循环依赖问题?我在 Spring MVC 中很新。谢谢。
  • 写一个自定义的{de,}序列化器?虽然我不确定如何告诉 Spring 使用它...

标签: spring jackson circular-dependency


【解决方案1】:

最后,我找到了在不触及现有 POJO 的情况下解决循环问题的 Mixin Annotations。

这里有Minin Annotations的参考:http://wiki.fasterxml.com/JacksonMixInAnnotations

以下是使用 Mixin 的简要步骤:

  1. 将 ObjectMapper 添加到您的 web-spring-servlet.xml

    <bean id="myFrontObjectMapper" class="my.anying.web.MyObjectMapper"></bean>
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper" ref="myObjectMapper"></property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    
  2. 实现 MyObjectMapper

    public class MyObjectMapper extends ObjectMapper {
        public MyObjectMapper() {
            this.registerModule(new MixinModule());
        }
    }
    
  3. 实现 MixinModule

    public class MixinModule extends SimpleModule {
    
        private static final long serialVersionUID = 8115282493071814233L;
    
        public MixinModule() {
            super("MixinModule", new Version(1, 0, 0, "SNAPSHOT", "me.anying",
                "web"));
        }
    
        public void setupModule(SetupContext context) {
            context.setMixInAnnotations(Target.class, TargetMixin.class);
        }
    }
    
  4. 完成。

现在 TargetMixin 类上的所有注解都将应用于 Target 类。

【讨论】:

    猜你喜欢
    • 2010-11-29
    • 1970-01-01
    • 2020-11-12
    • 2021-05-23
    • 2022-09-22
    相关资源
    最近更新 更多