基本上你需要的是
- 创建一个
AbstractMongoEventListener 来监听AfterConvertEvent 和BeforeSaveEvent 事件
- 实现
org.springframework.util.ReflectionUtils.FieldCallback 回调以对这些事件执行操作
- 在 Spring Data mongodb 配置类中将监听器注册为 Bean
听者:
public class EncryptionMongoEventListener extends AbstractMongoEventListener<Object> {
@Override
public void onBeforeSave(BeforeSaveEvent<Object> event) {
Object source = event.getSource();
DBObject dbObject = event.getDBObject();
ReflectionUtils.doWithFields(source.getClass(),
new EncryptCallback(source, dbObject),
ReflectionUtils.COPYABLE_FIELDS);
}
@Override
public void onAfterConvert(AfterConvertEvent<Object> event) {
Object source = event.getSource();
ReflectionUtils.doWithFields(source.getClass(),
new DecryptCallback(source),
ReflectionUtils.COPYABLE_FIELDS);
}
}
加密回调:
class EncryptCallback implements FieldCallback {
private final Object source;
private final DBObject dbObject;
public EncryptCallback(final Object source, final DBObject dbObject) {
this.source = source;
this.dbObject = dbObject;
}
@Override
public void doWith(Field field)
throws IllegalArgumentException, IllegalAccessException {
if (!field.isAnnotationPresent(/* your annotation */.class)) {
return;
}
ReflectionUtils.makeAccessible(field);
String plainText = (String) ReflectionUtils.getField(field, source);
String encryptedValue = /* your encryption of plainText */;
// update the value in DBObject before it is saved to mongodb
dbObject.put(field.getName(), encryptedValue);
}
}
解密回调:
class DecryptCallback implements FieldCallback {
private final Object source;
public DecryptCallback(Object source) {
this.source = source;
}
@Override
public void doWith(Field field)
throws IllegalArgumentException, IllegalAccessException {
if (!field.isAnnotationPresent(/* your annotation */.class)) {
return;
}
ReflectionUtils.makeAccessible(field);
String fieldValue = (String) ReflectionUtils.getField(field, source);
String decryptedValue = /* your decryption of fieldValue */;
// set the decrypted value in source Object
ReflectionUtils.setField(field, source, decryptedValue);
}
}
最后,将监听器注册为 Spring Data mongodb 配置类中的 bean
@Bean
public EncryptionMongoEventListener encryptionMongoEventListener() {
return new EncryptionMongoEventListener();
}