Skip to content

Commit 46ecf7a

Browse files
committed
Only unwrap when DataSource is a wrapper for required type
Closes gh-16863
1 parent da12ad0 commit 46ecf7a

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DataSourceUnwrapper.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2018 the original author or authors.
2+
* Copyright 2012-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -76,11 +76,14 @@ public static <T> T unwrap(DataSource dataSource, Class<T> target) {
7676

7777
private static <S> S safeUnwrap(Wrapper wrapper, Class<S> target) {
7878
try {
79-
return wrapper.unwrap(target);
79+
if (wrapper.isWrapperFor(target)) {
80+
return wrapper.unwrap(target);
81+
}
8082
}
8183
catch (Exception ex) {
82-
return null;
84+
// Continue
8385
}
86+
return null;
8487
}
8588

8689
private static class DelegatingDataSourceUnwrapper {

spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jdbc/DataSourceUnwrapperTests.java

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2018 the original author or authors.
2+
* Copyright 2012-2019 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
1616

1717
package org.springframework.boot.jdbc;
1818

19+
import java.sql.SQLException;
20+
1921
import javax.sql.DataSource;
2022

2123
import com.zaxxer.hikari.HikariDataSource;
@@ -27,6 +29,9 @@
2729
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
2830

2931
import static org.assertj.core.api.Assertions.assertThat;
32+
import static org.mockito.Mockito.mock;
33+
import static org.mockito.Mockito.verify;
34+
import static org.mockito.Mockito.verifyNoMoreInteractions;
3035

3136
/**
3237
* Tests for {@link DataSourceUnwrapper}.
@@ -91,6 +96,17 @@ public void unwrapDataSourceProxy() {
9196
.isSameAs(dataSource);
9297
}
9398

99+
@Test
100+
public void unwrappingIsNotAttemptedWhenDataSourceIsNotWrapperForTarget()
101+
throws SQLException {
102+
DataSource dataSource = mock(DataSource.class);
103+
DataSource actual = DataSourceUnwrapper.unwrap(dataSource,
104+
HikariDataSource.class);
105+
assertThat(actual).isNull();
106+
verify(dataSource).isWrapperFor(HikariDataSource.class);
107+
verifyNoMoreInteractions(dataSource);
108+
}
109+
94110
private DataSource wrapInProxy(DataSource dataSource) {
95111
return (DataSource) new ProxyFactory(dataSource).getProxy();
96112
}

0 commit comments

Comments
 (0)