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.
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.
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?
The Java versionWhich real resource the application uses in each environmentThe server's portThe 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.