Yasin
Yasin

Reputation: 2039

How to establish SSL connection with DB (SQL Server, PG), in a driver agnostic way?

I have an application that connects with a Database. The DB could be SQL Server, PG, etc. I need to configure the application to use SSL now.

I am using hibernate and configuring the datasources accordingly. I am using org.apache.commons.dbcp2.BasicDataSource as of now.

I understand that in order to connect to SQL Server using SSL, I need to use SQLServerDataSource. But then it would not work if someone decides to use PG database.

Is there any way to configure the individual datasources dynamically? Or is there a common datasource that I can use irrespective of the jdbc driver (mssql or pg) provided at the runtime?

Passing the JVM parameters like -Djavax.net.ssl.trustStore and -Djavax.net.ssl.trustStorePassword modifying the jdbc connection string are not an option.

I am using Spring (mostly XML configs) to bootstrap the application.

Upvotes: 1

Views: 353

Answers (1)

Apokralipsa
Apokralipsa

Reputation: 2724

In Spring you can replace the used data source class using profiles.

The key idea is that you can provide multiple definition of the same bean. Those definitions would be enclosed in separate <beans> element with different profile attribute.

<beans profile="embedded-db">
    <jdbc:embedded-database id="dataSource">
        <jdbc:script location="classpath:com/bank/config/sql/schema.sql"/>
        <jdbc:script location="classpath:com/bank/config/sql/test-data.sql"/>
    </jdbc:embedded-database>
</beans>
<beans profile="sql-server">
    <!-- Configuration of you SQL Server data source -->
</beans>
<beans profile="postgresql">
    <!-- Configuration of you PostgreSQL data source -->
</beans>

When running the application the configuration property spring.profiles.active needs to be set to choose one or more of the profiles.

Unfortunately, modern Spring documentation doesn't provide much help in setting up XML configs. I think they are now considered legacy.

Upvotes: 1

Related Questions