Running under a Tomcat 9 and JDK 1.8, using Spring 5, I am trying to configure a JNDI connection to use a DataSource.
If I configure Spring, through XML, I get my DataSource and everything seems to work fine. I configured the DataSource in my applicationContext.xml, in this way:
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/yages"
resource-ref="true"/>
If I use the AbstractAnnotationConfigDispatcherServletInitializer class to initialize Spring, my DataSource is created but when I try to get the connection it gives me the following error:
java.sql.SQLException: Data source is closed
at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2049)
The DataSource I try to create with this function:
@Bean(name = "dataSource")
public DataSource dataSource(Environment env) throws NamingException
{
DataSource datasource=null;
try {
JndiDataSourceLookup lookup = new JndiDataSourceLookup();
datasource= lookup.getDataSource("jdbc/yages");
datasource.getConnection();
System.out.println("\n\n!!Cogida la Conexion del DataSource correctamente!!");
return datasource;
} catch (SQLException ex) {
System.out.println("\n\n!!Error al coger la Conexion del DataSource!!\n\n");
ex.printStackTrace();
}
return datasource;
}
It seems that the DataSource takes it well, but the connection to the database is closed. However, if I use the DataSource, configured through XML, if it works well for me, I assume that it is not a problem neither of the connection to the database nor of the configuration of Tomcat.
Any idea why the connection is closed?
Thank you.