JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

javax.naming.NameNotFoundException: Name is not bound in this Context Exception

May 3, 2014 by Krishna Srinivasan Leave a Comment

When you are working with the JNDI look up, quite often you would encounter the javax.naming.NameNotFoundException thrown by your application. JNDI names are registered in the registery, if you try to access the name which is not registered or by the wrong format, you would get the javax.naming.NameNotFoundException. Lets look at the below code for accessing the JNDI names using InitialContext.

[code lang=”java”]
Context envEntryContext = (Context) new InitialContext().lookup("java:comp/env");
String mydata = (String)envEntryContext.lookup("varName");
[/code]

When you run the above code, if the name “varName” not found under the context “java:comp/env”, then you will get the below exception. You have correct the name for fixing this issue.

[code]
javax.naming.NameNotFoundException: Name [varName] is not bound in this Context. Unable to find [varName].
at org.apache.naming.NamingContext.lookup(NamingContext.java:819)
at org.apache.naming.NamingContext.lookup(NamingContext.java:167)
at javabeat.net.util.HelloServlet.doGet(HelloServlet.java:20)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.logging.log4j.core.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:66)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
[/code]

Filed Under: Java EE Tagged With: Java Exceptions, JNDI

Dependency Management with JNDI

August 29, 2013 by Manisha Patil Leave a Comment

In this article we will see an introduction to dependency management through JNDI (Java Naming and Directory Interface). We will see how to name resources with annotations and how to search dependencies are created. Furthermore, we see examples of using JNDI API and alternatives to search certain components.

The business logic of an application is not always independent, our implementation often depends on other resources that are in the application server such as JDBC, JMS, Session Bean and Entity Manager.

JNDI

What is JNDI?

To manage these dependencies, Java EE components provides references to resources that are defined in metadata annotations or external. These references are nothing more than a link named to the resources that can be dynamically determined at runtime within the application code or automatically by the container when the component instance is created.

Every reference has a name and a destination. The name is used by the application code to determine dynamically the reference. The server uses the destination information to find the feature that the application is looking for.

  • Annotations and Dependency Injection in EJB 3.0

Search for Dependency

The most traditional way of dependency management in Java EE is through search dependency in which the application code uses the Java Naming and Directory Interface (JNDI or) to locate a named reference.

The JNDI or Java Naming and Directory Interface is an API for accessing directory services. It allows client applications to discover and obtain data or objects via a name. Like all Java APIs, it is platform independent. Its two basic functions are :

  • Associate (map) a feature with name
  • Find a resource from its name.

All annotations resources support the name attribute that define the name of the reference. When the annotation feature is placed in the class definition, this attribute is mandatory. If the annotation is placed on an attribute or a setter method, the server will generate a default name. Usually annotations are put at the class level, and so the name is explicitly specified.

The name of the role is to provide a way for the client to locate the reference dynamically. All Java EE application server supports JNDI, and each component has its own local JNDI naming context that is called the environment naming context. The name of the reference is linked to the environment naming context, and when it is searched using the JNDI API, the server determines the reference and returns the reference destination.

Finding a dependency EJB

As an example we can consider the session bean below. In the example we have a dependency on a session bean by @ EJB annotation, the session bean is called “audit”, as defined in the “name” attribute. The attribute beanInterface only defines the business interface of the session bean that the client is concerned. @ PostConstruct in the session bean audit is located and stored in the attribute audit.

Context and InitialContext interfaces are defined both by the JNDI API. The lookup() method of the Context interface is the first point to return objects from a JNDI context. To find the reference audit, the application looks up the name java: comp/env/audit and makes a cast (conversion) result for the business interface AuditService.

The prefix java: comp/env/ added to the name of the reference to the server indicates that the environment naming context should be searched to find the reference. If the name is incorrect, an exception will be thrown when the search fails.

[java]
@ Stateless
@ EJB (name = "audit", beanInterface = AuditService.class)
public class implements DeptServiceBean DeptService {
private AuditService audit;
@ PostConstruct
public void init () {
try {
Context ctx = new InitialContext ();
audit = (AuditService) ctx.lookup ("java: comp/env/ audit");
} Catch (NamingException e) {
throw new EJBException (e);
}
}
// …
}
[/java]

Despite the above form to be valid and supported by large-scale Java EE components, we note that it is a little tricky to use it due to exception handling required by JNDI. EJBs also support an alternative syntax using a lookup() method of the interface EJBContext.

The interface EJBContext (and subinterfaces SessionContext and MessageDrivenContext) is available to any EJB and provide the bean with access to services at runtime such as timer services. The same example above is shown below using the lookup () method alternative. The instance SessionContext this example is provided via setter method.

Finding a dependency using EJB lookup

[java]
@ Stateless
@ EJB (name = "audit", beanInterface = AuditService.class)
public class implements DeptServiceBean DeptService {
SessionContext context;
AuditService audit;

public void setSessionContext (SessionContext context) {
this.context = context;
}

@ PostConstruct
public void init () {
audit = (AuditService) context.lookup ("audit");
}

// …

}
[/java]

The lookup() method of the EJBContext has two main advantages over the JNDI API:

  • First is the argument to the method is exactly the name that was specified on the resource reference.
  • The second advantage is that only runtime exceptions are thrown by the lookup() method, the other checked exceptions of API JNDI can be avoided. The management of exceptions are made automatically, but hidden from the client.

Summary

In this article we saw that an application depends on other components and we can use the search dependency to locate these components. One way is to use the JNDI API (Java Naming and Directory Interface) it allows client applications to discover and obtain data and objects via a name, or we can use an interface support to locate EJBs which in turn has some advantages in their use JNDI instead of the API.

Reference Articles on Dependency Injection

  • Lars Vogel on DI
  • Wikipedia Reference
  • Contexts and Dependency Injection
  • Joe on DI with Spring

Filed Under: Java Tagged With: JNDI

DataSource through Java Naming and Dictionary Interface (JNDI)

May 7, 2011 by Krishna Srinivasan Leave a Comment

This article is based on Lift in Action, to be published on July 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information.

Connecting to a Database

Introduction

Because Lift runs in any servlet container, you have several options for getting a database connection—just as you would in a traditional Java application.

DataSource through Java Naming and Dictionary Interface (JNDI)

That’s one hell of a title but don’t worry—it’s far, far simpler than it sounds! JNDI is one of those technologies that has been kicking around in the Java ecosystem for a long time and has changed as the years have passed. These days, most people are familiar with using JNDI to get a DataSource object for their applications through a servlet or application container such as Jetty or Tomcat.

If you want to run your application from a DataSource supplied by your container, you only need to do one of two things. The first (and more traditional) option is to add a reference to your web.xml file as shown in listing 1. This sets up the JDBC reference so it can be located via JNDI.

Listing 1 DataSource wire-up in web.xml

[code lang=”xml”]<resource-ref>
<res-ref-name>jdbc/liftinaction</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>[/code]

The second and Lift-specific route is to add one line of code in your Lift Boot class, as shown in listing 2. This is my preferred option when using JNDI because it is more in keeping with the Lift idioms of Boot configuration.

Listing 2 JNDI wire-up in Boot

[code lang=”java”]
DefaultConnectionIdentifier.jndiName = "jdbc/liftinaction"[/code]

You will need to configure your container to actually provide this DataSource object. Unfortunately, this is very product specific so I won’t labor that here; check the online documentation for the container you’re using.

Application connection

If you would rather not use JNDI or you want a quick and easy way to set up your database connection, Lift provides a helpful wrapper around the Java DriverManager class. Listing 3 shows an example of the code you need to have in your Boot class.

Listing 3 DriverManager JDBC wire-up

[code lang=”java”]import net.liftweb.mapper.{DB,DefaultConnectionIdentifier} #1
import net.liftweb.http.{LiftRules,S} #1
DB.defineConnectionManager(DefaultConnectionIdentifier, DBVendor) #2
LiftRules.unloadHooks.append( #3
() => DBVendor.closeAllConnections_!()) #3
S.addAround(DB.buildLoanWrapper) #4[/code]

As you can see, there is a little more going on here than in the JNDI example. For completeness I have included the import statements so that it is clear where the various types are held (#1). #2 defines a wire-up between the application-specific DBVendor (as defined in listing 4) and Lift‘s connection manager. #3 details what Lift should do when it’s shutting down in order to cleanly close any application database connections. #4 configures Lift‘s loan wrapper1 so that actions conducted on the DefaultConnectionIdentifier are transactional for the whole HTTP request cycle.

Listing 4 DBVendor definition

[code lang=”java”]object DBVendor extends StandardDBVendor(
Props.get("db.class").openOr("org.apache.derby.jdbc.EmbeddedDriver"),
Props.get("db.url").openOr("jdbc:derby:lift_example;create=true"),
Props.get("db.user"),
Props.get("db.pass"))[/code]

Listing 4 demonstrates making an extension on the StandardDBVendor trait from Lift‘s Mapper. This handles connection pooling for you by using Apache Commons Pool so that everything is taken care of for you. This DBVendor pulls its connection string and credentials from a properties file. If the file and the key pair do not exist, it will failover onto using the in-memory Derby database.

JNDI OR APPLICATION CONNECTION?

Choosing between JNDI or application connection is something that causes a fair amount of debate among developers and infrastructure folks. Traditionally, getting DataSource objects through JNDI was seen as a preferred route because it negated hard-coding any kind of connection or drivers into your application. The value of this benefit, while still present for some people, has probably waned somewhat with most developers. If we were looking for a more tangible value, you would look to the honed connection pooling and distributed transactions. Some people find great value here, while others do not. With libraries like Apache Commons Pool, it’s fairly simple to implement robust connection pooling in your application directly. So there is no real answer—it depends where and what you are deploying as to which will work best. To that end, keep abreast of both approaches and see what works for you.

In the code for the tutorial online, you will see that both mechanisms are supported within the application. JNDI is actually my preferred route for deployment, but many Lift sites run perfectly well on application connections.

Summary

We have covered options for getting a database connection through JNDI. You can add a reference to the web.xml file or add one line of code in the Lift Boot class.

Filed Under: Java Tagged With: JNDI

Accessing objects in JNDI using Spring

October 22, 2007 by Krishna Srinivasan Leave a Comment

1) Introduction

Spring provides support to access objects from the JNDI Repository. This article will begin with the JNDI concepts along with a sample JNDI Application. Then it will proceed with the various core supporting classes available in Spring for JNDI Integration. Following that, practical samples would be given to make things clear. The pre-requisite for this article is some basic introductory knowledge in Spring which can be got by reading the article in javabeat Introduction to Spring Web Framework.

also read:

  • Introduction to Spring Framework
  • Spring Tutorials
  • Spring Framework Books (recommended)
  • Book Review : Spring in Action

2) JNDI

2.1) Introduction

JNDI stands for Java Naming and Directory interface. It is a specification and API that can be used to access any type directory service. For example, a particular implementation of JNDI specification can be used to access the LDAP Repository. JNDI is used heavily by the J2EE Applications to store Application specific data and business objects.
Imagine the case of a J2EE Application, where it is having a Web module and a EJB Module. A Web module is used to handle the Http Request from the Browser client, process it and then will return the Http Response back to the client. It basically will contain a collection of Servlet components and JSP’s. The Web module may use the EJB module for accessing the Enterprise Beans for data manipulation. Suppose, say that we want to store data that is common to both Web and EJB Module. Where we can store this information, in the Web Module or in the EJB Module?. It doesn’t make sense to store the data in any of the Modules, because the data is a common data and it is not particularly restricted to any of the Modules.
Here comes the JNDI Repository. The Application Server Container will provide an implementation for the JNDI Repository for storing the global data (data that is common across the modules) and the clients (either the Enterprise Beans, or the Servlets or even the Application client) can use the JNDI API to query the information available in the JNDI Repository. It is also possible to store the Business Objects (like Session Beans, Message Driven beans) in the JNDI Repository. In this case, a Servlet may be the client in getting a reference to the Enterprise Bean from the Repository. It is not necessary for an Application Developer to manually store the Business Objects into the JNDI Repository as the Container will take care of all these things, like constructing the JNDI Tree, storing the Business objects etc.

3) JNDI Sample

3.1) Introduction

Let us see an example of how to store and access the information stored in the JNDI Repository. This sample Application stores two entries (one is of type String and the other one is of type Integer) in the JNDI Repository. The client is going to be the servlet which makes use of the JNDI Api for accessing the information in the JNDI Repository.

3.2) Jndi Access Servlet

The Servlet class makes use of the InitialContext for accessing the JNDI information. The method lookup() queries for the value of the string that is passed as a key. Then it makes use of the normal PrintWriter class to send the information back to the Browser client.
JndiAccessServlet.java

[code lang=”java”]package javabeat.net.articles.spring.jndi.introduction;

import java.io.*;
import javax.naming.*;
import javax.servlet.http.*;

public class JndiAccessServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {

InitialContext context = null;
String welcomeMessage = null;
Integer maxSessionCount = null;

try{
context = new InitialContext();

welcomeMessage = (String)context.lookup(
"java:comp/env/welcomeMessage");
maxSessionCount = (Integer)context.lookup(
"java:comp/env/maxSessionCount");
}
catch (NamingException exception){
exception.printStackTrace();
}

PrintWriter writer = response.getWriter();
writer.write("Data read from JNDI Respository :");
writer.write("Welcome Message –&gt;" + welcomeMessage);
writer.write("Max Session Count–&gt;" + maxSessionCount);

writer.close();
}
}[/code]

3.3) Web Configuration File

The following is the configuration file for the Web Application. It defines the various servlet definition(s) along with the JNDI Entries. Let us have a look into that file,

web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>
<servlet-name>JndiAccessServlet</servlet-name>
<servlet-class>
javabeat.net.articles.spring.jndi.introduction.JndiAccessServlet<
/servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>JndiAccessServlet</servlet-name>
<url-pattern>/jndiServlet</url-pattern>
</servlet-mapping>

<env-entry>
<env-entry-name>welcomeMessage</env-entry-name>
<env-entry-value>Hello All</env-entry-value>
<env-entry-type>java.lang.String</env-entry-type>
</env-entry>

<env-entry>
<env-entry-name>maxSessionCount</env-entry-name>
<env-entry-value>1000</env-entry-value>
<env-entry-type>java.lang.Integer</env-entry-type>
</env-entry>

</web-app>
[/code]

The first section in the Xml file defines a Servlet by name jndiAccessServlet. The servlet-mapping tag says that the Servlet can be accessed through the URL '/jndiServlet'. The rest of the section contains the definition of the JNDI Entries. The tag env-entry defines an environmental entry in the JNDI Repository. The name of the entry, along with its type and value are given in the form of env-entry-name, env-entry-type and env-entry-value tags.

4) Spring’s JNDI Support

4.1) Introduction

In this section, we will have a look over the various core classes/interfaces available in Spring for JNDI support. The following classes are going to be dealt in this section,

  • JndiTemplate
  • JndiCallback
  • JndiObjectFactoryBean

We will look into the above classes one by one.

4.2) Jndi Template

A Jndi Template provides a simplified interface for performing various operations like lookup, binding and rebinding in the JNDI Repository. There isn’t much difference in using this JndiTemplate class versus the traditional way of accessing the JNDI using the InitialContext class. However, the only advantage of using this class is that it provides a method for executing custom lookup logic through call-back mechanisms which will be covered in the subsequent sections.
The following code snippet creates a JndiTemplate object for querying the JNDI Repository,

[code lang=”java”]JndiTemplate template = new JndiTemplate();[/code]

When the client of the JNDI Repository is within the same container, then the above code will work fine. What if the client Application is a remote client? In such a case, we have to specify the information (like JNDI URL, username and password) while creating the JndiTemplate object. This can be achieved through the following code,

[code lang=”java”]Properties props = new Properties();
// Populate JNDI specific information here.
pros.put("Key", "Value");

JndiTemplate template = new JndiTemplate();
template.setEnvironment(props);[/code]

The operations that can be performed over the JNDI Repository are querying, binding and re-binding. These are achieved through the methods lookup(), bind() and rebind() respectively.

[code lang=”java”]template.bind("SomeKey", "SomeValue");
…
String value = (String)template.lookup("SomeKey");
template.rebind("SomeKey", "SomeValue");[/code]

4.3) Jndi Callback

Spring provides support for encapsulating the JNDI operation (like lookup, bind and rebind) as a command object. Thereby it can be reused as many times as required. For example, say that the JNDI operation wants to be logged, then we can define a new class implementing the JndiCallback interface and overriding the doInContext() method.
To make this custom logic to get executed, we have to call the JndiTemplate.execute() by passing an argument of type JndiCallback. This call-back mechanism is certainly powerful as the whole logic of JNDI operation is confined to a single unit thereby leading the way to do any type of customization like logging, caching etc.

4.4) Jndi Object Factory Bean

This Factory bean is responsible for querying the information from the JNDI Repository. Usage of this factory bean is as simple as making configuration in the Spring’s Configuration file. Example of using this Factory Bean is given in the later samples section. The default strategy for this Factory Bean is to lookup all the JNDI objects and cache it. However, this can be modified by specifying the properties (“lookupOnStartup” and “cache”) to appropriate values.
Even this can be done programmatically like the following,

[code lang=”java”]JndiObjectFactoryBean bean = ….;
bean.setLookupOnStartup(false);
bean.setCache(false);[/code]

5) JNDI and Spring Configuration – Example

5.1) Introduction

In this section, we will look at code snippets for the support classes in Spring for JNDI Integration.

5.2) Making use of JndiTemplate class

As we have already seen, making using of JndiTemplate class for accessing the JNDI Repository is no different than using the InitialContext class. The following Servlet makes use of JndiTemplate class for querying the JNDI Repository.
ServletUsingJndiTemplate.java

[code lang=”java”]package javabeat.net.articles.spring.jndi.introduction;

import java.io.*;
import javax.naming.*;
import javax.servlet.http.*;
import org.springframework.jndi.JndiTemplate;

public class ServletUsingJndiTemplate extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {

JndiTemplate template = new JndiTemplate();
String welcomeMessage = null;
Integer maxSessionCount = null;

try{
welcomeMessage = (String)template.lookup(
"java:comp/env/welcomeMessage");
maxSessionCount = (Integer)template.lookup(
"java:comp/env/maxSessionCount");
}catch(NamingException exception){
exception.printStackTrace();
}

PrintWriter writer = response.getWriter();
writer.write("Data read from JNDI Respository using Jndi Template:");
writer.write("Welcome Message –&gt;" + welcomeMessage);
writer.write("Max Session Count–&gt;" + maxSessionCount);
writer.close();
}
}[/code]

To invoke this Servlet, add the following entries in the web.xml file,
web.xml

[code lang=”xml”]
<servlet>
<servlet-name>ServletUsingJndiTemplate</servlet-name>
<servlet-class>
javabeat.net.articles.spring.jndi.introduction.ServletUsingJndiTemplate
</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ServletUsingJndiTemplate</servlet-name>
<url-pattern>/jndiServletUsingJndiTemplate</url-pattern>
</servlet-mapping>
[/code]

5.3) Using the Callback Mechanism

The Jndi Callback mechanism provides a way for encapsulating the operations related to JNDI into a single unit and thereby makes it callable from various places. The following sample shows the usage of this interface,
CustomJndiAccessForLogging.java

[code lang=”java”]package javabeat.net.articles.spring.jndi.introduction;

import javax.naming.Context;
import javax.naming.NamingException;
import org.springframework.jndi.JndiCallback;
import org.springframework.jndi.JndiTemplate;

public class CustomJndiAccessForLogging implements JndiCallback {

private String key;

public CustomJndiAccessForLogging(String key) {
this.key = key;
}

public Object doInContext(Context context) throws NamingException {
System.out.println("Start lookup operation");
Object value = context.lookup(key);
System.out.println("End lookup operation");
return value;
}
}[/code]

In the above class, we have added logging support whenever an JNDI operation is invoked. However for the above code to work, we have to use the JndiTemplate.execute() method as shown below,

[code lang=”java”]JndiTemplate template = new JndiTemplate();
CustomJndiAccessForLogging callback = new CustomJndiAccessForLogging("key");
Object result = template.execute(callback);[/code]

5.4) Configuring the Jndi Object Factory Bean

In this final section, we will see how to configure the Jndi Object Factory Bean for getting the information from JNDI Repository. Let us first represent a class for holding the values fetched from the Repository. The following code is the class definition for the same,
InfoFromJndi.java

[code lang=”java”]package javabeat.net.articles.spring.jndi.introduction;

public class InfoFromJndi {

private String welcomeMessage;
private Integer maxSessionCount;

public String getWelcomeMessage(){
return welcomeMessage;
}

public void setWelcomeMessage(String welcomeMessage){
this.welcomeMessage = welcomeMessage;
}

public Integer getMaxSessionCount(){
return maxSessionCount;
}

public void setMaxSessionCount(Integer maxSessionCount){
this.maxSessionCount = maxSessionCount;
}
}[/code]

Now, let us define the configuration file with the aim of populating the two properties welcomeMessage and maxSessionCount for the above class. Let us have a look at the following configuration file,
spring-jndi.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">

<bean id="infoFromJndi"
>

<property name="welcomeMessage">
<bean>
<property name="jndiName">
<value>java:comp/env/welcomeMessage</value>
</property>
</bean>
</property>

<property name="maxSessionCount">
<bean>
<property name="jndiName">
<value> java:comp/env/maxSessionCount</value>
</property>
</bean>
</property>

</bean>

</beans>
[/code]

Note that a new bean instance of type InfoFromJndi with name 'infoFromJndi' is created. Now the two properties 'welcomeMessage' and 'maxSessionCount' has to be populated with the values taken from JNDI. To make this possible, we have defined the property tag representing the property tag with the attribute name pointing to 'welcomeMessage' but we haven’t given the 'value' attribute. Instead, we have defined a nested Jndi Object Factory bean whose property name should point to the JNDI name, so that the value of this property can be fetched from the JNDI and the same can be assigned to the outer 'welcomeMessage' property. Same is the case for the 'maxSessionCount' property.

6) Conclusion

We have seen the introductory details for the various forms of support for Spring-JNDI Integration available in Spring. Using Spring for accessing the JNDI objects is very simple as it involves adding relevant information in the configuration file. The advantage of using Spring over the regular JNDI API is that we can take the full support of features like IOC and Dependency injection which will be available by default with Spring.

also read:

  • Introduction to Spring Framework
  • Introduction to Spring Web Flow (SWF)
  • Spring Framework Books (recommended)
  • Book Review : Spring in Action

Filed Under: Spring Framework Tagged With: JNDI, Spring

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved