Tuesday, August 04, 2009

Jackson 1.2: use Mix-In Annotations to reuse, decouple

After reviewing the "number #1 user favorite feature" of upcoming Jackson 1.2 release, let's check out the Author's cut. As cool as ability to use any constructor or factory method a POJO has, my favorite feature is this little feature called Mix-in Annotations.

1. What are Mix-in Annotations?

Mix-in annotations are annotations defined in a mix-in class (or interface), that are to be used to augment annotations of a target class (or interface). Augmenting means that annotations of the mix-in class are used as if they were directly included in target class. Another way to explain this is to think of "mixing in annotations" to mean "injecting annotations from mix-in class to a target class".

Simple enough? There are obviously many smaller details (which will be explained later on), but for now this definition should suffice.

2. Example use case

Definition itself only describes what the feature is and does, but not why it would be useful. So let's consider an example use case.

Let's say you are using a third-party (or legacy) library that has a class called Point, defined as:

  public final class Point {
    final private int x, y;
    public Point(int x, int y) {
      this.x = x;
      this.y = y;
    int x() { return x; }
    int y() { return y; }
    int getArea() { return x * y; }

Point class is used extensively; including being exchanged between services. This means it needs to be serialized and deserialized.

Now Point is a perfectly ok POJO (and even somewhat typical one), but not one easily usable with data binding frameworks, including Jackson 1.1. Problems are:

  • Bean naming convention is not used, so that properties "x" and "y" are not serializable using getter methods; nor are fields public for automatic detection
  • Method "getArea" implies a bean property (and would be auto-detected), but we do NOT want to serialize property "area", since it is just a derived value and not an actual property
  • No default constructor is defined, but a 2-argument "initializing" constructor (not a problem per se with 1.2, any more); and that constructor is not marked as something we can use

So how would we serialize such a POJO?

Two main approaches would be adding annotations to guide the process; or writing a custom serializer.

In this case, we can not modify Point class definition itself; and ideally do not want to write custom serializers and deserializers, unless we absolutely have to.

3. Solution using Mix-in Annotations

So here is how you could use mix-in annotations to make Point (JSON) serializable: first, define a mix-in annotation interface (class would do as well):

  interface MixIn {
    @JsonProperty("x") int x();
    @JsonProperty("y") int y();
    @JsonIgnore int getArea();

and then configure ObjectMapper to use that as a "mix-in" for Point like so:

  ObjectMapper mapper = new ObjectMapper();
  mapper.getSerializationConfig().addMixInAnnotations(Point.class, MixIn.class);

And voila! After doing this, Points would be serialized as containing integer properties "x" and "y"; not "area" as would happen by default.

Before considering the other part (deserialization), here are some notes on using Mix-in Annotations:

  • All annotation sets that Jackson recognizes (core annotations, JAXB extensions) can be mixed in
  • All kinds of annotations (member method, static method, field, constructor annotations) can be mixed in
  • Only method (and field) name and signature are used for matching annotations: access definitions (private etc) and method implementations are ignored. (hint: if you can, it often makes sense to define mix-in class as an [abstract?] sub-class of target class, and use @Override JDK annotation to ensure method name and signature match!)
  • Mix-ins work as expected within inheritance hierarchy: it is feasible (and useful) to attach mix-in annotations to super-classes -- if so, mix-in annotations can further be overridden by annotations sub-classes (of target) provide.

4. Works for deserialization, too (or: "Better with BYOC")

So far so good? So here's another mix-in to tackle deserialization part -- the need to indicate constructor to use, and its parameter binding.

  abstract class DeserMixIn { // must be class to define constructors!
    DeserMixIn(@JsonProperty("x") int x, @JsonProperty("y") int y) { }

and then just register this mix-in using ObjectMapper.getDeserializationConfig().addMixInAnnotations().
Note, too, that you could just create a single mix-in class to contain all annotations; they are here only separated for clarity.

It is also worth re-iterating that the ability to annotate "Creators" (constructors as well static factory methods) is the "other cool new feature" of Jackson 1.2.

So we can get Points out of JSON, so to speak.

5. So what IS the Point?

So the obvious first main benefit of this feature is that it makes it easier to work with legacy code; especially one you can not (or do not want to) modify by adding annotations. It is often good idea to let the sleeping code lie, unless you plan to do some significant refactoring. If it ain't broke, don't fix it.

But beyond this, it is also possible that perhaps you would ideally not add "special-purpose" (or perhaps, any at all) annotations to your POJOs. Arguably these annotations create a depedency to Jackson annotation classes, which should usually just be implementation details (assuming the main use for classes is not to serialize to JSON but do something else, aka "business logic"), and as such lead to unnecessary coupling of code.

So if you prefer to leave serialization-oriented annotations out of your biz-logic and data access/transfer classes, you could consider instead using Mix-in Annotations as the mechanism to associate necessary configuration information without introducing "wrong kind of" coupling. In a way, Mix-in Annotations can be viewed kind of Aspect-Oriented (or maybe Inversion-of-Control) feature. They allow injecting runtime serialization/deserialization configuration information, using dynamic (but non-intrusive: no code is modified!) mechanism.

7. Keep on Innovating!

One more thing: I think that this feature is one of the first features that is truly innovative with Jackson. There are many things that are improved, and perhaps even clever. But Mix-in Annotations is something I haven't seen in other libraries yet. Given this, I am curious to learn how users feel about it -- leave a comment here, or send email: let me know how you really feel!

The idea is of course to continue innovating. 1.3 is planned to contain similarly innovative features to make it possible, for example, to bind objects from regular Maps (and vice versa). Why? Well, wouldn't it be nice to create POJOs out of those nice little Java properties files? I think so too!

blog comments powered by Disqus

Sponsored By

Related Blogs

(by Author (topics))

Powered By

About me

  • I am known as Cowtowncoder
  • Contact me at@yahoo.com
Check my profile to learn more.