问题
I have an application that has a datasource. Everytime I undeploy the application from the manager GUI the datasources are being closed. When I try to redeploy, the datasource stays closed and throws the following exception:
{
"status" : "DOWN",
"error" : "org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Data source is closed"
}
Caused by: java.sql.SQLException: Data source is closed
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1362) ~[tomcat-dbcp.jar:7.0.53]
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044) ~[tomcat-dbcp.jar:7.0.53]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139) ~[hibernate-core-4.3.1.Final.jar:4.3.1.Final]
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380) ~[hibernate-core-4.3.1.Final.jar:4.3.1.Final]
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228) ~[hibernate-core-4.3.1.Final.jar:4.3.1.Final]
... 81 common frames omitted
Restarting the server solves this issue but that is not an acceptable solution for a production application.
I have a different application with a different datasource with the same issue.
Both application are using Spring Boot version 1.1.4 with Tomcat 7. One of the applications was converted to Spring Boot and didn't have the datasource issues before conversion.
Below is how I create the Datasource currently in my Spring Boot Application.java file.
@Bean()
public DataSource dataSource() {
return new JndiDataSourceLookup().getDataSource("com.datasource.CONSUMER");
}
How do I stop this from happening?
回答1:
This isn't specific to Spring Boot, it's standard Spring behaviour.
By default, Spring will infer a bean's destroy method. From the javadoc for @Bean:
As a convenience to the user, the container will attempt to infer a destroy method against an object returned from the
@Beanmethod. For example, given an@Beanmethod returning an Apache Commons DBCPBasicDataSource, the container will notice theclose()method available on that object and automatically register it as thedestroyMethod. This 'destroy method inference' is currently limited to detecting only public, no-arg methods named 'close' or 'shutdown'.
The javadoc goes on to describe how to disable this behaviour:
To disable destroy method inference for a particular
@Bean, specify an empty string as the value, e.g.@Bean(destroyMethod="")
You need to update your dataSource() method:
@Bean(destroyMethod="")
public DataSource dataSource() {
return new JndiDataSourceLookup().getDataSource("com.datasource.CONSUMER");
}
来源:https://stackoverflow.com/questions/25149969/why-does-datasources-close-on-tomcat-7-undeploy-with-spring-boot