It is said in Spring javadoc article about DriverManagerDataSource
class, that this class is very simple and that it is recommended
to use a JNDI DataSource provided by the container. Such a
DataSource
can be exposed as aDataSource
bean in a Spring ApplicationContext viaJndiObjectFactoryBean
The question is: how to accomplish this?
For example if I wish to have DataSource bean to access my custo mysql database, what I require then? What to write in context configuration etc?
In your spring class, You can inject a bean annotated like as
and You add this in your context.xml
You can declare the JNDI resource in tomcat's server.xml using
back to context.xml de spring add this
if, like this exmple you are injecting connection to database, make sure that MySQL jar is present in the tomcat lib directory, otherwise tomcat will not be able to create the MySQL database connection pool.
According to Apache Tomcat 7 JNDI Datasource HOW-TO page there must be a resource configuration in web.xml:
That works for me
Documentation: C.2.3.1
<jee:jndi-lookup/>
(simple)Example:
You just need to find out what JNDI name your appserver has bound the datasource to. This is entirely server-specific, consult the docs on your server to find out how.
Remember to declare the
jee
namespace at the top of your beans file, as described in C.2.3 The jee schema.If using Spring's XML schema based configuration, setup in the Spring context like this:
Alternatively, setup using simple bean configuration like this:
You can declare the JNDI resource in tomcat's server.xml using something like this:
And reference the JNDI resource from Tomcat's web context.xml like this:
Reference documentation:
Edit: This answer has been updated for Tomcat 8 and Spring 4. There have been a few property name changes for Tomcat's default datasource resource pool setup.
Assuming you have a "sampleDS" datasource definition inside your tomcat configuration, you can add following lines to your
applicationContext.xml
to access the datasource using JNDI.You have to define the namespace and schema location for
jee
prefix using:With Spring's JavaConfig mechanism, you can do it like so: