Search code examples
javaspringjbossjndi

How to connect to DataSources dynamically at runtime?


This is the situation - I have JBOSS EAP 6.4 setup as my application server and have defined some JNDI data sources in it. The name and number of the data sources can vary across environments. I need to write a webservice which takes JNDI data source and query as input. It should connect to the respective data source and execute the query.

So the JNDI data source name should not be hardcoded in the application and it should be taken as input at runtime.

I cannot use the below spring config to define the datasource since this would make it hardcoded -

<bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:jboss/datasources/myDS2"/>
</bean>

I would like to do something like:

<bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="${dataSourceInput}"/>
</bean>

where ${dataSourceInput} is the input for the webservice.

Please, let me know how to achieve it.

Update --

I do not want the datasource name to be passed in as a JVM argument or through a parameter file. The datasource name has to be passed as an input to the webservice. The above code snippet is probably not the right way to do it. Probably this is not possible through spring config file.

Please, let me know if there is any other way to achieve the same.


Solution

  • After search for a while I found the answer I was looking for.

    I can create the datasource form the JNDI name which is taken as input to the webservice as below.

    dataSourceInput = <input from the webservice>
    ctx = new InitialContext();
    DataSource ds = (DataSource) ctx.lookup(dataSourceInput);
    

    Reference - http://www.journaldev.com/2513/tomcat-datasource-jndi-example-java