WebSphere Tutorial · WebSphere Liberty · Lesson 8 of 23

JNDI and Resource References

How applications find data sources, queues and settings by name, and why resource references keep code portable.

Members can save this page, take notes and track progress. See membership · Sign in

Names for resources

The server registers resources in JNDI under names such as jdbc/orders. Code gets them by injection:

@Resource(lookup = "jdbc/orders")
private DataSource orders;

Better still, declare a resource reference (a local name) and bind it to the real JNDI name at deployment:

@Resource(name = "jdbc/ordersDb")          // looked up as java:comp/env/jdbc/ordersDb
private DataSource orders;
<!-- Liberty: bind the reference -->
<webApplication location="orders.war">
  <web-bnd><resource-ref name="jdbc/ordersDb" binding-name="jdbc/orders"/></web-bnd>
</webApplication>

On traditional WAS the binding is set when installing the application (admin console or wsadmin) or in ibm-web-bnd.xml.

One resource reference, different bindings per environmentTry it yourself
jndi = {"jdbc/orders-prod": "PostgreSQL orders (prod)", "jdbc/orders-test": "PostgreSQL orders (test)"}

def lookup(reference, bindings):
    return jndi[bindings[reference]]

for env, bindings in {"test": {"jdbc/ordersDb": "jdbc/orders-test"},
                      "prod": {"jdbc/ordersDb": "jdbc/orders-prod"}}.items():
    print(f"{env:4}: code asks for java:comp/env/jdbc/ordersDb -> {lookup('jdbc/ordersDb', bindings)}")

Output

test: code asks for java:comp/env/jdbc/ordersDb -> PostgreSQL orders (test)
prod: code asks for java:comp/env/jdbc/ordersDb -> PostgreSQL orders (prod)

Test yourself

What does a resource reference let you change without touching code?

  1. The Java version
  2. Which real resource the application uses in each environment
  3. The server's port
  4. The application's class loader
Show answer

Answer: Which real resource the application uses in each environment

The binding maps the reference to an environment's JNDI name.

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake