Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does an application that uses Spring's SimpleNamingContextBuilder know to search its directory for resources?

Tags:

java

spring

jndi

How does an application that uses Spring's SimpleNamingContextBuilder as its JNDI provider know to search its directory for resources? What links the application to the Spring naming directory? For example, how does the JndiObjectFactoryBean bean in this earlier answer know to find resource my-db in the Spring directory? Doesn't JndiObjectFactoryBean require a context environment with property java.naming.factory.initial set to some implementation of interface InitialContextFactory? What should the value of java.naming.factory.initial be when using SimpleNamingContextBuilder as the JNDI provider?

like image 364
Derek Mahar Avatar asked Apr 15 '11 21:04

Derek Mahar


2 Answers

In a nutshell, If want to mock JNDI tree with mock InitialContext in unit tests , SimpleNamingContextBuilder can be used. I instantiated SimpleNamingContextBuildeit in a startup method of test and successfully creates a in-memory InitialContext. e.g. in a spring test class..

@BeforeClass
    public static void setupJndi() throws Exception {
    SimpleNamingContextBuilder.emptyActivatedContextBuilder();
    Context context = new InitialContext();
    context.bind("java:comp/env/jms/ConnectionFactory",myJmsConnectionFactory);
   }
like image 136
supernova Avatar answered Sep 28 '22 06:09

supernova


Java runtime class NamingManager serves as the link between a Java application and its naming directory. When a SimpleNamingContextBuilder activates, it installs itself to static member InitialContextFactoryBuilder in NamingManager. When the application creates an InitialContext to retrieve the JNDI context, class InitialContext delegates to NamingManager, which in turn asks the IntialContextFactoryBuilder (in this case, SimpleNamingContextBuilder) to create an IntialContextFactory, which ultimately creates the InitialContext.

JndiObjectFactoryBean doesn't need an explicit context environment because SimpleNamingContextBuilder provides the InitialContextFactory to the NamingManager and JndiObjectFactoryBean uses the NamingManager to retrieve its resources. So, in the earlier answer, JndiObjectFactoryBean "knows" to search the Spring naming directory for resource my-db because SimpleNamingContextBuilder has established itself as the JNDI provider in the NamingManager.

like image 31
Derek Mahar Avatar answered Sep 28 '22 07:09

Derek Mahar