使用属性添加,替换绑定

命名示例讨论了如何使用bind(), rebind()DirContextinterface包含接受属性的这些方法的重载版本。在将绑定或子上下文添加到名称空间时,可以使用这些DirContext方法将属性与对象关联。例如,您可以创建一个Person对象并将其绑定到名称空间,并同时关联有关该Person对象的属性。

添加具有属性的绑定

DirContext.bind()用于向上下文添加具有属性的绑定。它接受对象的名称,要绑定的对象以及一组属性作为参数。

// Create the object to be bound
Fruit fruit = new Fruit("orange");

// Create attributes to be associated with the object
Attributes attrs = new BasicAttributes(true); // case-ignore
Attribute objclass = new BasicAttribute("objectclass");
objclass.add("top");
objclass.add("organizationalUnit");
attrs.put(objclass);

// Perform bind
ctx.bind("ou=favorite, ou=Fruits", fruit, attrs);

This example创建一个类Fruit的对象,并将其与名称"ou=favorite"绑定到相对于ctx的名为"ou=Fruits"的上下文中。此绑定具有"objectclass"属性。如果随后在ctx中查找名称"ou=favorite, ou=Fruits",则将获得fruit对象。如果然后获得"ou=favorite, ou=Fruits"的属性,则将获得用于创建对象的那些属性。以下是此示例的输出。

# java Bind
orange
attribute: objectclass
value: top
value: organizationalUnit
value: javaObject
value: javaNamingReference
attribute: javaclassname
value: Fruit
attribute: javafactory
value: FruitFactory
attribute: javareferenceaddress
value: #0#fruit#orange
attribute: ou
value: favorite

显示的额外属性和属性值用于存储有关对象(fruit)的信息。这些额外的属性将在本教程中详细讨论。

如果要两次运行此示例,则第二次try将失败,并带有NameAlreadyBoundException。这是因为名称"ou=favorite"已经绑定在"ou=Fruits"上下文中。为了第二次try成功,您将不得不使用rebind\(\)

替换具有属性的绑定

DirContext.rebind()用于添加或替换绑定及其属性。它接受与bind\(\)相同的参数。但是,rebind\(\)的语义要求,如果名称已经绑定,则它将不绑定,并且新给定的对象和属性也将绑定。

// Create the object to be bound
Fruit fruit = new Fruit("lemon");

// Create attributes to be associated with the object
Attributes attrs = new BasicAttributes(true); // case-ignore
Attribute objclass = new BasicAttribute("objectclass");
objclass.add("top");
objclass.add("organizationalUnit");
attrs.put(objclass);

// Perform bind
ctx.rebind("ou=favorite, ou=Fruits", fruit, attrs);

运行this example时,它将替换bind()示例创建的绑定。

# java Rebind
lemon
attribute: objectclass
value: top
value: organizationalUnit
value: javaObject
value: javaNamingReference
attribute: javaclassname
value: Fruit
attribute: javafactory
value: FruitFactory
attribute: javareferenceaddress
value: #0#fruit#lemon
attribute: ou
value: favorite