添加,用属性替换绑定
原文: https://docs.oracle.com/javase/tutorial/jndi/ops/bindattr.html
命名实例讨论了如何使用 bind()
, rebind()
。 DirContext
接口包含接受属性的这些方法的重载版本。您可以使用这些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”
进入名为“ou = Fruits”
的上下文,相对于ctx
。该绑定具有“objectclass”
属性。如果您随后在ctx
中查找了名称“ou =最爱,ou =水果”
,那么您将获得水果
对象。如果你得到“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
)。这些额外的属性将在跟踪中更详细地讨论。
如果您要运行此示例两次,则第二次尝试将失败并显示 NameAlreadyBoundException
。这是因为名称“ou = favorite”
已经绑定在“ou = Fruits”
上下文中。要成功的第二次尝试,你必须使用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
时,它会替换 绑定()
示例创建的绑定。
# 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