jr.
jr.

Reputation: 4675

Where to store database passwords in a spring application or use JNDI?

Seems like a simple task. I have a webapp which requires a database connection. I'd like to be able to drop an updated .war file on this app server and load a new version without having to re-edit an applicationConfig.xml file to specify the database connection parameters for production.

Is using the container to setup the data source and then referencing it from JNDI the preferred way to go? I think it is cleaner having it all defined in the spring .xml file, but I can't come up with a clean way to allow the production password to be set only once as we roll out new versions.

So, how do you specify your database connection information in a spring application so that you can upgrade it without having to re-edit the files?

If you use JNDI, how do you handle setting up of your tests since the JNDI is not going to be available outside of the container?

Thanks!

Upvotes: 2

Views: 1155

Answers (2)

toolkit
toolkit

Reputation: 50227

One approach is for your Spring configuration file to be composed of fragments related to specific layers in your application.

One such fragment could contain your DataSource defintion. For production, this fragment would use a jee:jndi-lookup. And then for test, have a different fragment would use a DriverManagerDataSource ?

Update:

If you want to change the datasource after deployment, then you can use this technique, along with changing the which datasource is injected into your other beans using a PropertyPlaceholderConfigurer as explained in an old post I wrote

eg:

<bean class="foo.bar.SomeClassNeedingDataSource"">
    <property name="dataSource" ref="${the.datasource.to.inject}" />
</bean>

<jee:jndi-lookup id="jndiDataSource" ... />

<bean id="driverManagerDataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    ...
</bean>

# the properties file
the.datasource.to.inject = jndiDataSource
#the.datasource.to.inject = driverManagerDataSource

Upvotes: 0

axtavt
axtavt

Reputation: 242686

The typical way to externalize database connection properties is to store them in a .properties file and load using <context:property-placeholder .../> . Then you can have different .properties files for testing and production.

If you choose JNDI, you can use a Spring's mock JNDI support for testing.

Upvotes: 2

Related Questions