I have two ways to create datasource:
Inside spring context
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mkyongjava" />
<property name="username" value="root" />
<property name="password" value="password" />
Tomcat JNDI
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/UsersDB"/>
What are the benefits and problems of creating the datasource using spring or using tomcat jndi ?
There is nothing like good practice among this. The good one is the one which is good for use case. They both have pros and cons.
When u have use cases where u are trying to deploy the apps on a server environment where multiple apps share a common datasource or datasource components are managed by the Server administration then probably the best way to use is through a JNDI context. The server has the DataSource kept ready so that the application can directly get that object, bind to itself and use the datasource.
When u have use case where application runs inside a embedded server container or cloud containers where the server also is embedded along the build packs creating datasource with in the application and using them would be a good solution. Also in non web application environments creating datasource would be good.
To summarize, use cases where datasource is non managed by the application better to go for a JNDI context.
Try to figure out what is the deployment model of your application and figure out what is good for u. Also try to use a datasourcepool implementations to improve performance like DBCP, C3P0 or Hikarcp.