Skip to main content
 首页 » 编程设计

spring中使用 Jackson 解决循环依赖错误,无需使用注释

2024年11月24日16bjzhanghao

目前,我正在使用 Spring 框架编写一些 web 应用程序。对于所有 @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 类的代码,因此我无法在其中使用任何注释。 那么如何在不使用注解的情况下解决这个问题呢?

预先感谢您的任何建议!

请您参考如下方法:

最后,我找到了 Mixin Annotations 来解决循环问题,而无需触及现有的 POJO。

这里有 Minin 注解的引用: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 类。