Search code examples
springjdbcdatasourcejndi

Using JdbcTemplate with a "Non-Spring-Bean" JNDI DataSource


Page 342 of spring-framework-reference.pdf (bundled with spring-framework-3.1.0.M2) states, "The JdbcTemplate can be used within a DAO implementation through direct instantiation with a DataSource reference." However, it goes on to say, "The DataSource should always be configured as a bean in the Spring IoC container."

Does anyone know why the DataSource shouldn't be provided to a JdbcTemplate from a plain-old JNDI lookup outside of the Spring container, e.g. How to programatically use Spring's JdbcTemplate?


Solution

  • "The DataSource should always be configured as a bean in the Spring IoC container."

    It appears that this note is intended to clarify the preceding statement:

    "The JdbcTemplate can be used within a DAO implementation through direct instantiation with a DataSource reference, or be configured in a Spring IoC container and given to DAOs as a bean reference."

    I believe the information these statements are trying to convey is that when you're configuring a DAO in Spring, you can either:

    1. inject the DataSource directly into the DAO and create the JdbcTemplate in code yourself, or
    2. you can make the JdbcTemplate a Spring bean as well, inject the DataSource into the JdbcTemplate, and inject the JdbcTemplate into the DAO.

    The note, then, means that if Spring is managing the DAO and its dependencies, the DataSource must be a Spring bean in either case, as it needs to be injected either into the DataSource for use in constructing the JdbcTemplate (case 1) or into the JdbcTemplate itself (case 2).

    I wouldn't take it to mean that a DataSource used in a JdbcTemplate must always be managed by Spring and only Spring. The note does give that impression. It's probably worth filing a bug against.