添加,用属性替换绑定

原文: https://docs.oracle.com/javase/tutorial/jndi/ops/bindattr.html

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

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

  1. // Create the object to be bound
  2. Fruit fruit = new Fruit("orange");
  3. // Create attributes to be associated with the object
  4. Attributes attrs = new BasicAttributes(true); // case-ignore
  5. Attribute objclass = new BasicAttribute("objectclass");
  6. objclass.add("top");
  7. objclass.add("organizationalUnit");
  8. attrs.put(objclass);
  9. // Perform bind
  10. ctx.bind("ou=favorite, ou=Fruits", fruit, attrs);

This example 创建类 `Fruit `的对象并将其绑定到名称“ou = favorite”进入名为“ou = Fruits”的上下文,相对于ctx 。该绑定具有“objectclass”属性。如果您随后在ctx中查找了名称“ou =最爱,ou =水果”,那么您将获得水果对象。如果你得到“ou = favorite,ou = Fruits”的属性,你将得到创建对象的那些属性。以下是此示例的输出。

  1. # java Bind
  2. orange
  3. attribute: objectclass
  4. value: top
  5. value: organizationalUnit
  6. value: javaObject
  7. value: javaNamingReference
  8. attribute: javaclassname
  9. value: Fruit
  10. attribute: javafactory
  11. value: FruitFactory
  12. attribute: javareferenceaddress
  13. value: #0#fruit#orange
  14. attribute: ou
  15. value: favorite

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

如果您要运行此示例两次,则第二次尝试将失败并显示 NameAlreadyBoundException。这是因为名称“ou = favorite”已经绑定在“ou = Fruits”上下文中。要成功的第二次尝试,你必须使用rebind()

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

  1. // Create the object to be bound
  2. Fruit fruit = new Fruit("lemon");
  3. // Create attributes to be associated with the object
  4. Attributes attrs = new BasicAttributes(true); // case-ignore
  5. Attribute objclass = new BasicAttribute("objectclass");
  6. objclass.add("top");
  7. objclass.add("organizationalUnit");
  8. attrs.put(objclass);
  9. // Perform bind
  10. ctx.rebind("ou=favorite, ou=Fruits", fruit, attrs);

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

  1. # java Rebind
  2. lemon
  3. attribute: objectclass
  4. value: top
  5. value: organizationalUnit
  6. value: javaObject
  7. value: javaNamingReference
  8. attribute: javaclassname
  9. value: Fruit
  10. attribute: javafactory
  11. value: FruitFactory
  12. attribute: javareferenceaddress
  13. value: #0#fruit#lemon
  14. attribute: ou
  15. value: favorite