CuriousMind
CuriousMind

Reputation: 8903

Should Datasource be managed by Spring or web-container?

I am trying to understand in real life Enterprise applications (e.g. web-application, using Spring Framework) who should manage the Data source? I can think of two ways:

(i) Data source defined in Spring configuration and on need basis the application can get the data source from the Spring container.

(ii) Data source defined in web-container (for example) and then the application can get the data source from the container.

Now, I have following questions:

Q1) In scenario (i) I believe we can use Spring's DI to inject the Data source as it is managed by Spring. Is it correct?

Q2) In scenario (ii), the only way to get the Data source would be using the JNDI lookup, as the data source is configured in the container, and hence Spring won't be able to do DI. Is the correct?

Q3) When the Data source is managed by the Spring Container, would it be able to handle connection pooling, global transaction etc., if so, how? Does it internally use some third party libraries to achieve all this?

Any detailed information on this really appreciated.

Upvotes: 3

Views: 673

Answers (1)

Jiri Tousek
Jiri Tousek

Reputation: 12440

Basically:

  • Spring-defined data source makes you independent on the container, and it is easier to deploy your application
  • Container-defined data source gives the power and responsibility for the data source configuration in hands of the server admin instead of programmer
    • This follows arguably a better responsibility / role separation
    • It allows the server admin to maintain and update the data source without knowing details of your application
    • It solves a common "no DB passwords in plaintext" requirement, making the container responsible for securing the password instead of you

It is possible to refer to a JNDI resource in Spring configuration, so Spring will do the lookup for you and it will be available for DI.

You can use third-party libraries (e.g. Apache commons-dbcp) to do connection pooling for Spring-managed data sources (I've done so on enterprise projects).

Spring supports DB transaction management using the built-in TransactionManager. According to documentation, it seems JPA is only available if the data source is defined in container.

Upvotes: 5

Related Questions