Only unwrap when DataSource is a wrapper for required type

Closes gh-16863
This commit is contained in:
Andy Wilkinson 2019-05-22 12:52:10 +01:00
parent da12ad0ca5
commit 46ecf7a928
2 changed files with 23 additions and 4 deletions

View File

@ -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.
@ -76,11 +76,14 @@ public final class DataSourceUnwrapper {
private static <S> S safeUnwrap(Wrapper wrapper, Class<S> target) {
try {
return wrapper.unwrap(target);
if (wrapper.isWrapperFor(target)) {
return wrapper.unwrap(target);
}
}
catch (Exception ex) {
return null;
// Continue
}
return null;
}
private static class DelegatingDataSourceUnwrapper {

View File

@ -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.
@ -16,6 +16,8 @@
package org.springframework.boot.jdbc;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariDataSource;
@ -27,6 +29,9 @@ import org.springframework.jdbc.datasource.DelegatingDataSource;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Tests for {@link DataSourceUnwrapper}.
@ -91,6 +96,17 @@ public class DataSourceUnwrapperTests {
.isSameAs(dataSource);
}
@Test
public void unwrappingIsNotAttemptedWhenDataSourceIsNotWrapperForTarget()
throws SQLException {
DataSource dataSource = mock(DataSource.class);
DataSource actual = DataSourceUnwrapper.unwrap(dataSource,
HikariDataSource.class);
assertThat(actual).isNull();
verify(dataSource).isWrapperFor(HikariDataSource.class);
verifyNoMoreInteractions(dataSource);
}
private DataSource wrapInProxy(DataSource dataSource) {
return (DataSource) new ProxyFactory(dataSource).getProxy();
}