首页 > 解决方案 > Morphia - 具有自定义读取器和写入器的自定义字段

问题描述

我想添加一个具有默认行为的自定义类型的字段。我的目的是处理所有类型的秘密字段:

例如:我在用户类上有密码字段,我希望密码字段以某种方式加密,所以而不是:

  @Entity
    public static class User {
        String name;
        String pwd;
        String pwdToken
        public User() {
        }
        public User( string name, string password ) {
            super();
            this.pwd = password;
        }
    }

然后从外部管理解密和加密 - 服务或控制器

我会有类似的东西:

  @Entity
    public static class User {
        String name;
        SecretField pwd;
       
        public User() {
        }
        public User( string name, string password ) {
            super();
               this.name = name;
            // this.pwd.set(password)
        }
    }

   public final class SecretField implements Serializable {
    
      private static final long serialVersionUID = 1L;
  
      private String encryptedContent;
      private String token;
    
     public SecretField(String content) {
               this.token = generateToken();
               this.encryptedContent = decrypt(content, this.token);
     }

     // when especially called the decrypted pwd will be returned
     public decrypt(){
        decrypt(encryptedContent, token)
     }  

     //here I should override the default output object - return this.encryptedContent instead of whole object
     //???
     
   }

这样,每次我有一个秘密字段时,我都可以使用这个类,加密将自动完成,我不需要单独管理每个控制器上的。在更新和插入时,密码将作为解密字符串从客户端发送,并在获取加密字符串时返回。

吗啡可以吗?

标签: javamorphia

解决方案


您可以在 2.0 中编写自定义编解码器来为您执行此操作。在此之前,您可以编写一个生命周期事件处理程序来执行此操作。可以在https://morphia.dev找到相关文档


推荐阅读