Connection failed through JNDI

1

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.

    
asked by chuchip 30.08.2018 в 07:53
source

1 answer

0

I have already found the problem. Spring when it does an undeploy, by default it destroys the objects. In this case when destroying the DataSource, it closes the connection to the database and the next time, it no longer works. The solution is to create the Bean with this order:

@Bean(name = "dataSource", destroyMethod = "")

This way Spring does not destroy the Bean and everything works correctly.

    
answered by 30.08.2018 в 13:19