Reputation: 6116
I have a Java 8/Maven/Spring Boot project. I am using Javers to audit changes in my application however I have a custom annotation I created that is placed above the fields in a class that I want audited if changed. Here's a sample class:
public class Foo {
@AuditThis
private final String someString;
private final int someInt;
@AuditThis
private final double someDouble;
private final long someLong;
@AuditThis
private final List<String> someList;
}
When calling javers.compare(foo1, foo2)
I want it to only compare the fields with the annotation @AuditThis
on top. Therefore, in this case it would only compare the someString
, someDouble
, someList
fields of the Foo
object.
I know you can set up a custom comparator so I tried doing something like this:
public class AuditThisComparator implements CustomPropertyComparator<Object, ValueChange> {
@Override
public ValueChange compare(final Object left,
final Object right,
final GlobalId globalId,
final Property property) {
ValueChange change = null;
Field[] leftFields = left.getClass().getDeclaredFields();
Field[] rightFields = right.getClass().getDeclaredFields();
int upperBound = leftFields.length;
for (int i = 0; i < upperBound; i++) {
if (return i < leftFields.length && leftFields[i].getAnnotation(AuditThis.class) != null) {
change = new ValueChange(globalId, property.getName(), left, right);
break;
}
}
return change;
}
}
And then register it like so:
Javers javers = JaversBuilder.javers()
.registerCustomComparator(new AuditThisComparator(), Object.class)
.build();
But this custom comparator never gets called when I do .compare()
. Any ideas what I'm doing wrong or if there's an easier way to go about this?
I can't use the @DiffIgnore
because the custom annotation I made takes in some special arguments the user can specify that we use in our auditing process.
Upvotes: 1
Views: 2391
Reputation: 3496
JaVers has @DiffInclude
property designed for that. see https://javers.org/documentation/domain-configuration/#property-level-annotations
Put it on fields you want to audit and others would be ignored by JaVers. This is the right way, you cant register your annotation. Writing custom comparators seems like a bad idea because you would have to duplicate JaVers diff algorithm.
Upvotes: 5