Skip to content

Adds spring.datasource.lazy-connection property to enable Lazy DataSource support #15968

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -57,7 +57,8 @@ public class DataSourceAutoConfiguration {
@Configuration
@Conditional(EmbeddedDatabaseCondition.class)
@ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
@Import(EmbeddedDataSourceConfiguration.class)
@Import({ EmbeddedDataSourceConfiguration.class,
LazyConnectionDataSourceConfiguration.class })
protected static class EmbeddedDatabaseConfiguration {

}
Expand All @@ -67,7 +68,8 @@ protected static class EmbeddedDatabaseConfiguration {
@ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
@Import({ DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class,
DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.Generic.class,
DataSourceJmxConfiguration.class })
DataSourceJmxConfiguration.class,
LazyConnectionDataSourceConfiguration.class })
protected static class PooledDataSourceConfiguration {

}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -149,6 +149,11 @@ public class DataSourceProperties implements BeanClassLoaderAware, InitializingB
*/
private Charset sqlScriptEncoding;

/**
* Whether datasource must be wrapped in a LazyConnectionDataSourceProxy.
*/
private boolean lazyConnection = false;

private EmbeddedDatabaseConnection embeddedDatabaseConnection = EmbeddedDatabaseConnection.NONE;

private Xa xa = new Xa();
Expand Down Expand Up @@ -478,6 +483,14 @@ public void setXa(Xa xa) {
this.xa = xa;
}

public boolean getLazyConnection() {
return this.lazyConnection;
}

public void setLazyConnection(boolean lazyConnection) {
this.lazyConnection = lazyConnection;
}

/**
* XA Specific datasource settings.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.boot.autoconfigure.jdbc;

import javax.sql.DataSource;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;

/**
* {@link BeanPostProcessor} to wrap a {@link DataSource} with a
* {@link LazyConnectionDataSourceProxy}.
*
* @author Dmytro Nosan
*/
class LazyConnectionDataSourceBeanPostProcessor implements BeanPostProcessor {

@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof DataSource) {
return new LazyConnectionDataSourceProxy((DataSource) bean);
}
return bean;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.jdbc;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;

/**
* Configuration to register {@link LazyConnectionDataSourceBeanPostProcessor}, if a
* {@code spring.datasource.lazy-connection} property is present and value is
* {@code true}.
*
* @author Dmytro Nosan
*/
@Configuration
@ConditionalOnClass(LazyConnectionDataSourceProxy.class)
@ConditionalOnProperty(prefix = "spring.datasource", name = "lazy-connection", havingValue = "true")
class LazyConnectionDataSourceConfiguration {

@Bean
public static LazyConnectionDataSourceBeanPostProcessor lazyConnectionDataSourceBeanPostProcessor() {
return new LazyConnectionDataSourceBeanPostProcessor();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import org.springframework.boot.jdbc.XADataSourceWrapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
Expand All @@ -59,6 +60,7 @@
EmbeddedDatabaseType.class })
@ConditionalOnBean(XADataSourceWrapper.class)
@ConditionalOnMissingBean(DataSource.class)
@Import(LazyConnectionDataSourceConfiguration.class)
public class XADataSourceAutoConfiguration implements BeanClassLoaderAware {

private ClassLoader classLoader;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -38,6 +38,7 @@
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.jdbc.DataSourceUnwrapper;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.boot.test.context.FilteredClassLoader;
Expand All @@ -46,7 +47,9 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.util.StringUtils;

import static org.assertj.core.api.Assertions.assertThat;
Expand Down Expand Up @@ -140,7 +143,7 @@ public void commonsDbcp2ValidatesConnectionByDefault() {
Arrays.asList("com.zaxxer.hikari", "org.apache.tomcat"), (dataSource) -> {
assertThat(dataSource.getTestOnBorrow()).isTrue();
assertThat(dataSource.getValidationQuery()).isNull(); // Use
// Connection#isValid()
// Connection#isValid()
});
}

Expand Down Expand Up @@ -224,6 +227,64 @@ public void testDataSourceIsInitializedEarly() {
.isTrue());
}

@Test
public void ignoreLazyConnectionOverriddenDataSource() {
this.contextRunner.withPropertyValues("spring.datasource.lazy-connection=true")
.withUserConfiguration(TestDataSourceConfiguration.class)
.run((context) -> assertThat(context).getBean(DataSource.class)
.isInstanceOf(BasicDataSource.class));
}

@Test
public void lazyConnectionEmbeddedDataSource() {
assertLazyDataSource(EmbeddedDatabase.class,
Arrays.asList("com.zaxxer.hikari", "org.apache.tomcat",
"org.apache.commons.dbcp2"),
(dataSource) -> assertThat(DataSourceUnwrapper.unwrap(dataSource,
SimpleDriverDataSource.class)).isNotNull()
.extracting(SimpleDriverDataSource::getUrl).asString()
.startsWith("jdbc:h2:mem:testdb"));
}

@Test
public void lazyConnectionDefaultDataSource() {
assertLazyDataSource(HikariDataSource.class, Collections.emptyList(),
(dataSource) -> assertThat(dataSource.getJdbcUrl())
.startsWith("jdbc:hsqldb:mem:testdb"));
}

@Test
public void lazyConnectionTomcatIsFallback() {
assertLazyDataSource(org.apache.tomcat.jdbc.pool.DataSource.class,
Collections.singletonList("com.zaxxer.hikari"),
(dataSource) -> assertThat(dataSource.getUrl())
.startsWith("jdbc:hsqldb:mem:testdb"));
}

@Test
public void lazyConnectionCommonsDbcp2IsFallback() {
assertLazyDataSource(BasicDataSource.class,
Arrays.asList("com.zaxxer.hikari", "org.apache.tomcat"),
(dataSource) -> assertThat(dataSource.getUrl())
.startsWith("jdbc:hsqldb:mem:testdb"));
}

private <T extends DataSource> void assertLazyDataSource(Class<T> expectedType,
List<String> hiddenPackages, Consumer<T> consumer) {
FilteredClassLoader classLoader = new FilteredClassLoader(
StringUtils.toStringArray(hiddenPackages));
this.contextRunner.withPropertyValues("spring.datasource.lazy-connection=true")
.withClassLoader(classLoader).run((context) -> {
DataSource dataSource = context.getBean(DataSource.class);
assertThat(dataSource)
.isInstanceOf(LazyConnectionDataSourceProxy.class);
DataSource targetDataSource = ((LazyConnectionDataSourceProxy) dataSource)
.getTargetDataSource();
assertThat(targetDataSource).isInstanceOf(expectedType);
consumer.accept(expectedType.cast(targetDataSource));
});
}

private <T extends DataSource> void assertDataSource(Class<T> expectedType,
List<String> hiddenPackages, Consumer<T> consumer) {
FilteredClassLoader classLoader = new FilteredClassLoader(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,6 +16,8 @@

package org.springframework.boot.autoconfigure.jdbc;

import java.sql.Connection;

import javax.sql.DataSource;
import javax.sql.XADataSource;

Expand All @@ -28,8 +30,10 @@
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;

/**
Expand All @@ -39,6 +43,17 @@
*/
public class XADataSourceAutoConfigurationTests {

@Test
public void lazyXaDataSource() {
ApplicationContext context = createContext(WrapExisting.class,
"spring.datasource.lazy-connection=true");
assertThat(context.getBean(DataSource.class))
.isInstanceOf(LazyConnectionDataSourceProxy.class);
XADataSource source = context.getBean(XADataSource.class);
MockXADataSourceWrapper wrapper = context.getBean(MockXADataSourceWrapper.class);
assertThat(wrapper.getXaDataSource()).isEqualTo(source);
}

@Test
public void wrapExistingXaDataSource() {
ApplicationContext context = createContext(WrapExisting.class);
Expand Down Expand Up @@ -111,9 +126,11 @@ private static class MockXADataSourceWrapper implements XADataSourceWrapper {
private XADataSource dataSource;

@Override
public DataSource wrapDataSource(XADataSource dataSource) {
public DataSource wrapDataSource(XADataSource dataSource) throws Exception {
this.dataSource = dataSource;
return mock(DataSource.class);
DataSource mockDataSource = mock(DataSource.class);
doReturn(mock(Connection.class)).when(mockDataSource).getConnection();
return mockDataSource;
}

public XADataSource getXaDataSource() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3631,7 +3631,22 @@ TIP: See <<howto.adoc#howto-configure-a-datasource,the "`How-to`" section>> for
advanced examples, typically to take full control over the configuration of the
DataSource.

[[boot-features-configure-lazy-datasource]]
=== Configure a lazy DataSource
Lazy `javax.sql.DataSource` (`org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy`) allows delaying the obtaining of a `javax.sql.Connection` until a `javax.sql.Connection` is really required.
JDBC transaction control can happen without fetching a `javax.sql.Connection` from the pool or communicating with the database.

`Connection` initialization properties like `auto-commit`, `transaction-isolation` and `read-only`
will be kept and applied to the actual JDBC `javax.sql.Connection` as soon as an actual `Connection` is fetched.
Consequently, _commit_ and _rollback_ calls will be *ignored* if no Statements have been created.

To *enable* this feature `spring.datasource.lazy-connection=true` must be set, by default this feature is disabled.

[NOTE]
====
Lazy `javax.sql.DataSource` proxy needs to return wrapped Connections in order to handle lazy fetching of an actual JDBC `Connection`.
Use `javax.sql.Connection#unwrap` or `static org.springframework.boot.jdbc.DataSourceUnwrapper#unwrap` to retrieve the native JDBC `Connection`.
====

[[boot-features-embedded-database-support]]
==== Embedded Database Support
Expand Down Expand Up @@ -3755,8 +3770,6 @@ example:
spring.datasource.tomcat.test-on-borrow=true
----



[[boot-features-connecting-to-a-jndi-datasource]]
==== Connection to a JNDI DataSource
If you deploy your Spring Boot application to an Application Server, you might want to
Expand Down