首页 > 解决方案 > 缺少 Spring LDAP 对象目录映射器注释的属性

问题描述

我正在尝试使用 Spring LDAP 的对象目录映射将对象写入 LDAP 服务器。该对象使用@Entity注释,并且几个字段使用@Attribute注释。

只要填充了所有带注释的字段,一切正常。但是如果字段的值,比如myattribute,是 null 或空字符串,LdapTemplate的createupdate方法会抛出错误。服务器拒绝该操作,并抱怨“属性 'myattribute' 的属性值 '' 在语法上不正确”

LDAP 模式允许缺少“myattribute”(它是相关对象类的“可能”属性),但如果存在,则不允许为空(它具有目录字符串语法)。我无法更改架构。

当相应的 POJO 字段为空或为空时,是否有某种方法可以让 Spring LDAP 省略“myattribute”,而不是尝试使用空值创建属性?

标签: javaspringldapspring-ldap

解决方案


我找到了一个解决方案,它对于我的应用程序可能不是最优雅的,但它确实有效。与其将 Java 字段声明为String类型,不如将其声明为List类型。然后,在 setter 中,如果值为空白或 null,我将列表长度设置为零,而不是设置单个空值。

@Entry( objectClasses={"myObject"} )
public class MyDataContainer {

    @Attribute("myattribute")
    private List<String> _myattribute = new ArrayList<String>(1);

    public String getMyAttribute() {
        if ( _myattribute.length() > 0 ) {
            return _myattribute.get(0);
        }
        return null;
    }

    public void setMyAttribute( String value ) {
        _myattribute.clear();
        value = ( value == null ) ? "" : value.trim();
        if ( ! "".equals( value ) ) {
            _myattribute.add( value );
        }
    }
}

推荐阅读