添加,替换或删除绑定

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

上下文接口包含添加替换去除上下文中的绑定的方法。

Context.bind() 用于向上下文添加绑定。它接受对象的名称和要绑定的对象作为参数。


继续之前:本课程中的示例要求您添加架构。您必须关闭 LDAP 服务器中的模式检查,或将本教程附带的 the schema 添加到服务器。这两项任务通常由目录服务器的管理员执行。请参阅 LDAP 设置课程。


  1. // Create the object to be bound
  2. Fruit fruit = new Fruit("orange");
  3. // Perform the bind
  4. ctx.bind("cn=Favorite Fruit", fruit);

This example 创建类 `Fruit `的对象并将其绑定到名称“cn = Favorite Fruit” ]在上下文ctx中。如果您随后在ctx中查找名称“cn =收藏水果”,那么您将获得水果对象。注意,要编译Fruit类,需要 `FruitFactory `类。

如果您要运行此示例两次,则第二次尝试将失败并显示 NameAlreadyBoundException。这是因为名称“cn = Favorite Fruit”已被绑定。对于第二次尝试成功,你必须使用 rebind()

rebind()用于添加或替换绑定。它接受与bind()相同的参数,但是语义是这样的,如果名称已经绑定,那么它将被解除绑定并且新绑定的对象将被绑定。

  1. // Create the object to be bound
  2. Fruit fruit = new Fruit("lemon");
  3. // Perform the bind
  4. ctx.rebind("cn=Favorite Fruit", fruit);

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

The binding to lemon is being replaced by a bind to orange.

要删除绑定,请使用 unbind()

  1. // Remove the binding
  2. ctx.unbind("cn=Favorite Fruit");

This example ,运行时,去除由 结合()[[]创建的结合rebind()`` 的例子。