Using JNDI binding for constants from the server configuration files

You can bind constants into the default Java™ Naming and Directory Interface (JNDI) namespace from the server configuration files by using the <jndiEntry> element on Liberty.

About this task

Open Liberty Documentation for JNDI binding in version 21.0.0.5 and later is available on the Open Liberty website.

The default JNDI namespace is available in Liberty to provide bindings to miscellaneous objects required by applications. Any data sources declared in the server configuration files are available in the default JNDI namespace. Additionally, you can bind Java strings and primitive data types in the configuration file into JNDI namespace. These constants are then made available to an application at run time, providing a simple and portable way to pass configuration values into the application.

For more information about the JNDI naming, see Naming.

Procedure

  1. Add a constant into the default JNDI namespace by specifying the jndi-1.0 Liberty feature in the server.xml file of the Liberty server.
    <featureManager>
       <feature>jndi-1.0</feature>
    </featureManager>
  2. Bind constants into the JNDI namespace by specifying the <jndiEntry> elements with jndiName and value attributes in the server.xml file.
    <jndiEntry jndiName="schoolOfAthens/defaultAdminUserName" value='"plato"' />
    <jndiEntry jndiName="schoolOfAthens/defaultAdminPassword" value='"republic"' />
    If you want to bind an instance of java.net.URL into the JNDI namespace, use the jndiURLEntry configuration:
    <jndiURLEntry jndiName="urls/OpenLiberty" value="http://www.openliberty.io" />
  3. Look up the constants from an application by using a JNDI context with the following code:
      Object jndiConstant = new InitialContext().lookup("schoolOfAthens/defaultAdminUserName");
      String defaultAdmin = (String) jndiConstant;
    Note:
    See the following examples of Java literals:
    • The string "Hello, world" followed by a newline character:
      <jndiEntry jndiName="a" value='"Hello, world.\n"' />
    • The integer with a binary value 1010101:
        <jndiEntry jndiName="b" value="0b1010101" />
    • The single character 'X':
         <jndiEntry jndiName="c" value="'X'" />
    • The double-precision floating point number 1.0:
         <jndiEntry jndiName="d" value="1.0D" />

    For more information about <jndiEntry> element, see Java Naming and Directory Interface.