How can I replace jndi search for data source without application server

I want to check out some of the new features that are part of the internal web application. This new code uses a database connection, usually provided by the application server (tomcat).

I do not want to recreate the entire web application on my local computer in order to test the new code, since I only need to run one function.

Does anyone know how I can โ€œspoofโ€ a Context or data source to get the database configuration without actually creating an instance of the web application on the server?

+7
java datasource jndi
source share
3 answers

Using Spring SimpleNamingContextBuilder and Apache BasicDataSource , you can do something like this (usually I have this in a static block in test classes that need JNDI):

BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(db_driver_name); dataSource.setUrl(db_connection_url); dataSource.setUsername(db_username); dataSource.setPassword(db_password); SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder(); builder.bind(jndi_name, dataSource); builder.activate(); 

The jndi_name value might look like this: java:comp/env/jdbc/my-db

Once this is set up, code that normally looks for a database connection through JNDI should work. The above code, for example, will work with this Spring config:

 <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jdbc/my-db"/> </bean> 
+4
source share

The solutions listed here look a little simpler than what I came up with about a year ago when I had to do the same. Basically, I made my very simple DataSource implementation and added it to a new initial context.

http://penguindreams.org/blog/running-beans-that-use-application-server-datasources-locally/

+1
source share

With TomcatJNDI, you can access every JNDI resource configured in Tomcat, as it was in your web application. The code to achieve it is simple and looks like

 TomcatJNDI tomcatJNDI = new TomcatJNDI(); tomcatJNDI.processContextXml(contextXmlFile); tomcatJNDI.start(); DataSource ds = (DataSource) InitialContext.doLookup("java:comp/env/path/to/datasource") 

Go here to learn more about this.

0
source share

All Articles