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?
问题:
回答1:
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);
}
回答2:
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
.