Domanda

Currently, I'm writing some webapp using Spring framework. For all @RestController APIs, I use Jackson to generate Json objects.

The @RestController looks like

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

But there are circular dependency problems when two objects have bi-direction-reference. For example, there are two POJO classes as follows:

class A {
    private B b;

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


class B {
    private A a;

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

I can solve it easily by this way, using annotations: http://java.dzone.com/articles/circular-dependencies-jackson

But that's not my point.

Now, I cannot change the code of A and B classes, so that I cannot use any annotations in them. Then how can I solve this problem without using annotations?

Thanks in advance for any advice!

È stato utile?

Soluzione

Finally, I've found the Mixin Annotations to solve the circular without touching the existing POJO.

There is a reference of Minin Annotations here: http://wiki.fasterxml.com/JacksonMixInAnnotations

The following is a brief steps to use Mixin:

  1. Add ObjectMapper to your 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. Implement MyObjectMapper

    public class MyObjectMapper extends ObjectMapper {
        public MyObjectMapper() {
            this.registerModule(new MixinModule());
        }
    }
    
  3. Implement 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. Done.

Now all annotations on TargetMixin class will be applied to Target class.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top