通常,你需要是
- 创建
AbstractMongoEventListener
监听AfterConvertEvent
和BeforeSaveEvent
事件
- 实施
org.springframework.util.ReflectionUtils.FieldCallback
回调对这些事件做动作
- 注册听众为豆在Spring数据mongodb配置类
听众:
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数据MongoDB的配置类豆
@Bean
public EncryptionMongoEventListener encryptionMongoEventListener() {
return new EncryptionMongoEventListener();
}
我做了一个库,只是你想要的:https:// gi thub.com/agoston/spring-data-mongodb-encrypt –
请看看这篇文章,它符合您的要求 http://www.rhyous.com/2012/05/26/aop-encrypting-with- aspectj-using-an-annotation/ –