Create separate class for callback

This commit is contained in:
alex-semenyuk 2015-08-23 11:13:01 +02:00
parent 67d636aaf9
commit a3e8f9f60e
2 changed files with 57 additions and 24 deletions

View File

@ -0,0 +1,53 @@
package org.baeldung.event;
import java.lang.reflect.Field;
import org.baeldung.annotation.CascadeSave;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.util.ReflectionUtils;
public class CascadeCallback implements ReflectionUtils.FieldCallback {
private Object source;
private MongoOperations mongoOperations;
public CascadeCallback(final Object source, final MongoOperations mongoOperations) {
this.source = source;
this.setMongoOperations(mongoOperations);
}
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
ReflectionUtils.makeAccessible(field);
if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(CascadeSave.class)) {
final Object fieldValue = field.get(getSource());
if (fieldValue != null) {
FieldCallback callback = new FieldCallback();
ReflectionUtils.doWithFields(fieldValue.getClass(), callback);
getMongoOperations().save(fieldValue);
}
}
}
public Object getSource() {
return source;
}
public void setSource(Object source) {
this.source = source;
}
public MongoOperations getMongoOperations() {
return mongoOperations;
}
public void setMongoOperations(MongoOperations mongoOperations) {
this.mongoOperations = mongoOperations;
}
}

View File

@ -1,37 +1,17 @@
package org.baeldung.event;
import org.baeldung.annotation.CascadeSave;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
public class CascadeSaveMongoEventListener extends AbstractMongoEventListener<Object> {
@Autowired
private MongoOperations mongoOperations;
@Override
public void onBeforeConvert(final Object source) {
ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
ReflectionUtils.makeAccessible(field);
if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(CascadeSave.class)) {
final Object fieldValue = field.get(source);
if (fieldValue != null) {
FieldCallback callback = new FieldCallback();
ReflectionUtils.doWithFields(fieldValue.getClass(), callback);
mongoOperations.save(fieldValue);
}
}
}
});
ReflectionUtils.doWithFields(source.getClass(), new CascadeCallback(source, mongoOperations));
}
}
}