Review doc on advanced datasource customization

Closes gh-7652
pull/8037/merge
Stephane Nicoll 8 years ago
parent 4760a1a6e1
commit 4efa4590f8

@ -1690,16 +1690,17 @@ a| `log4j2.json` +
[[howto-configure-a-datasource]]
=== Configure a DataSource
To override the default settings just define a `@Bean` of your own of type `DataSource`.
As explained in
<<spring-boot-features.adoc#boot-features-external-config-3rd-party-configuration>> you
can easily bind it to a set of `Environment` properties:
=== Configure a custom DataSource
To configure your own `DataSource` define a `@Bean` of that type in your configuration.
Spring Boot will reuse your `DataSource` anywhere one is required, including database
initialization. If you need to externalize some settings, you can easily bind your
`DataSource` to the environment (see
<<spring-boot-features.adoc#boot-features-external-config-3rd-party-configuration>>).
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
@Bean
@ConfigurationProperties(prefix="datasource.fancy")
@ConfigurationProperties(prefix="app.datasource")
public DataSource dataSource() {
return new FancyDataSource();
}
@ -1707,82 +1708,157 @@ can easily bind it to a set of `Environment` properties:
[source,properties,indent=0]
----
datasource.fancy.jdbcUrl=jdbc:h2:mem:mydb
datasource.fancy.username=sa
datasource.fancy.poolSize=30
app.datasource.url=jdbc:h2:mem:mydb
app.datasource.username=sa
app.datasource.pool-size=30
----
Spring Boot also provides a utility builder class `DataSourceBuilder` that can be used
to create one of the standard data sources (if it is on the classpath), or you can just
create your own. If you want to reuse the customizations of `DataSourceProperties`, you
can easily initialize a `DataSourceBuilder` from it:
Assuming that your `FancyDataSource` has regular JavaBean properties for the url, the
username and the pool size, these settings will be bound automatically before the
`DataSource` is made available to other components. The regular
<<howto-initialize-a-database-using-spring-jdbc,database initialization>> will also happen
(so the relevant sub-set of `spring.datasource.*` can still be used with your custom
configuration).
You can apply the same principle if you are configuring a custom JNDI `DataSource`:
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
@Bean
@ConfigurationProperties(prefix="datasource.mine")
public DataSource dataSource(DataSourceProperties properties) {
return properties.initializeDataSourceBuilder()
// additional customizations
.build();
@Bean(destroyMethod="")
@ConfigurationProperties(prefix="app.datasource")
public DataSource dataSource() throws Exception {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource("java:comp/env/jdbc/YourDS");
}
----
Spring Boot also provides a utility builder class `DataSourceBuilder` that can be used
to create one of the standard data sources (if it is on the classpath). The builder can
detect the one to use based on the ones available on the classpath and it also auto
detects the driver based on the JDBC url.
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
include::{code-examples}/jdbc/BasicDataSourceExample.java[tag=configuration]
----
To run an app with that `DataSource`, all that is needed really is the connection
information; pool-specific settings can also be provided, check the implementation that
is going to be used at runtime for more details.
[source,properties,indent=0]
----
app.datasource.url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass
app.datasource.pool-size=30
----
There is a catch however. Because the actual type of the connection pool is not exposed,
no keys are generated in the metadata for your custom `DataSource` and no completion is
available in your IDE (The `DataSource` interface doesn't expose any property). Also, if
you happen to _only_ have Hikari on the classpath, this basic setup will not work because
Hikari has no `url` parameter (but a `jdbcUrl` parameter). You should have to rewrite
your configuration as follows:
[source,properties,indent=0]
----
app.datasource.jdbc-url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass
app.datasource.maximum-pool-size=30
----
You can fix that by forcing the connection pool to use and return a dedicated
implementation rather than `DataSource`. You won't be able to change the implementation
at runtime but the list of options will be explicit.
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
include::{code-examples}/jdbc/SimpleDataSourceExample.java[tag=configuration]
----
You can even go further by leveraging what `DataSourceProperties` does for you, that is
providing a default embedded database if no url is provided with a sensible username and
password for it. You can easily initialize a `DataSourceBuilder` from the state of any
`DataSourceProperties` so you could just as well inject the one Spring Boot creates
automatically. However, that would split your configuration in two namespaces: url,
username, password, type and driver on `spring.datasource` and the rest on your custom
namespace (`app.datasource`). To avoid that, you can redefine a custom
`DataSourceProperties` on your custom namespace:
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
include::{code-examples}/jdbc/ConfigurableDataSourceExample.java[tag=configuration]
----
This setup puts you _in pair_ with what Spring Boot does for you by default, except that
a dedicated connection pool is chosen (in code) and its settings are exposed in the same
namespace. Because `DataSourceProperties` is taking care of the `url`/`jdbcUrl`
translation for you, you can configure it like this:
[source,properties,indent=0]
----
spring.datasource.url=jdbc:h2:mem:mydb
spring.datasource.username=sa
datasource.mine.poolSize=30
app.datasource.url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass
app.datasource.maximum-pool-size=30
----
In this scenario, you keep the standard properties exposed by Spring Boot with your
custom `DataSource` arrangement. By adding `@ConfigurationProperties`, you can also
expose additional implementation-specific settings in a dedicated namespace.
NOTE: Because your custom configuration chooses to go with Hikari, `app.datasource.type`
will have no effect. In practice the builder will be initialized with whatever value you
might set there and then overridden by the call to `.type()``.
See _<<spring-boot-features.adoc#boot-features-configure-datasource>>_ in the
'`Spring Boot features`' section and the
{sc-spring-boot-autoconfigure}/jdbc/DataSourceAutoConfiguration.{sc-ext}[`DataSourceAutoConfiguration`]
class for more details.
[TIP]
====
You could also do that if you want to configure a JNDI data-source.
[[howto-two-datasources]]
=== Configure Two DataSources
If you need to configure multiple data sources, you can apply the same tricks that are
described in the previous section. You must, however, mark one of the `DataSource`
`@Primary` as various auto-configurations down the road expect to be able to get one by
type.
If you create your own `DataSource`, the auto-configuration will back off. In the example
below, we provide the _exact_ same features set than what the auto-configuration provides
on the primary data source:
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
@Bean(destroyMethod="")
@ConfigurationProperties(prefix="datasource.mine")
public DataSource dataSource() throws Exception {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource("java:comp/env/jdbc/YourDS");
}
include::{code-examples}/jdbc/SimpleTwoDataSourcesExample.java[tag=configuration]
----
====
TIP: `fooDataSourceProperties` has to be flagged `@Primary` so that the database
initializer feature uses your copy (should you use that).
Both data sources are also bound for advanced customizations. For instance you could
configure them as follows:
[[howto-two-datasources]]
=== Configure Two DataSources
Creating more than one data source works the same as creating the first one. You might
want to mark one of them as `@Primary` if you are using the default auto-configuration for
JDBC or JPA (then that one will be picked up by any `@Autowired` injections).
[source,properties,indent=0]
----
app.datasource.foo.type=com.zaxxer.hikari.HikariDataSource
app.datasource.foo.maximum-pool-size=30
[source,java,indent=0,subs="verbatim,quotes,attributes"]
app.datasource.bar.url=jdbc:mysql://localhost/test
app.datasource.bar.username=dbuser
app.datasource.bar.password=dbpass
app.datasource.bar.max-total=30
----
@Bean
@Primary
@ConfigurationProperties(prefix="datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix="datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
Of course, you can apply the same concept to the secondary `DataSource` as well:
[source,java,indent=0,subs="verbatim,quotes,attributes"]
----
include::{code-examples}/jdbc/CompleteTwoDataSourcesExample.java[tag=configuration]
----
This final example configures two data sources on custom namespaces with the same logic
than what Spring Boot would do in auto-configuration.
[[howto-use-spring-data-repositories]]

@ -0,0 +1,48 @@
/*
* Copyright 2012-2017 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.jdbc;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Example configuration for configuring a very basic custom {@link DataSource}.
*
* @author Stephane Nicoll
*/
public class BasicDataSourceExample {
/**
* A configuration that exposes an empty {@link DataSource}.
*/
@Configuration
static class BasicDataSourceConfiguration {
// tag::configuration[]
@Bean
@ConfigurationProperties("app.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
// end::configuration[]
}
}

@ -0,0 +1,76 @@
/*
* Copyright 2012-2017 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.jdbc;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
* Example configuration for configuring two data sources with what Spring Boot does
* in auto-configuration.
*
* @author Stephane Nicoll
*/
public class CompleteTwoDataSourcesExample {
/**
* A complete configuration that exposes two data sources.
*/
@Configuration
static class CompleteDataSourcesConfiguration {
// tag::configuration[]
@Bean
@Primary
@ConfigurationProperties("app.datasource.foo")
public DataSourceProperties fooDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@Primary
@ConfigurationProperties("app.datasource.foo")
public DataSource fooDataSource() {
return fooDataSourceProperties()
.initializeDataSourceBuilder()
.build();
}
@Bean
@ConfigurationProperties("app.datasource.bar")
public DataSourceProperties barDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@ConfigurationProperties("app.datasource.bar")
public DataSource barDataSource() {
return barDataSourceProperties()
.initializeDataSourceBuilder()
.build();
}
// end::configuration[]
}
}

@ -0,0 +1,61 @@
/*
* Copyright 2012-2017 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.jdbc;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
* Example configuration for configuring a configurable custom {@link DataSource}.
*
* @author Stephane Nicoll
*/
public class ConfigurableDataSourceExample {
/**
* A configuration that define dedicated settings and reuse
* {@link DataSourceProperties}.
*/
@Configuration
static class ConfigurableDataSourceConfiguration {
// tag::configuration[]
@Bean
@Primary
@ConfigurationProperties("app.datasource")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@ConfigurationProperties("app.datasource")
public HikariDataSource dataSource(DataSourceProperties properties) {
return (HikariDataSource) properties.initializeDataSourceBuilder()
.type(HikariDataSource.class)
.build();
}
// end::configuration[]
}
}

@ -0,0 +1,53 @@
/*
* Copyright 2012-2017 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.jdbc;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Example configuration for configuring a simple {@link DataSource}.
*
* @author Stephane Nicoll
*/
public class SimpleDataSourceExample {
/**
* A simple configuration that exposes dedicated settings.
*/
@Configuration
static class SimpleDataSourceConfiguration {
// tag::configuration[]
@Bean
@ConfigurationProperties("app.datasource")
public HikariDataSource dataSource() {
return (HikariDataSource) DataSourceBuilder.create()
.type(HikariDataSource.class)
.build();
}
// end::configuration[]
}
}

@ -0,0 +1,73 @@
/*
* Copyright 2012-2017 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.jdbc;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
* Example configuration for configuring a configurable secondary {@link DataSource} while
* keeping the auto-configuration defaults for the primary one.
*
* @author Stephane Nicoll
*/
public class SimpleTwoDataSourcesExample {
/**
* A simple configuration that exposes two data sources.
*/
@Configuration
static class SimpleDataSourcesConfiguration {
// tag::configuration[]
@Bean
@Primary
@ConfigurationProperties("app.datasource.foo")
public DataSourceProperties fooDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@Primary
@ConfigurationProperties("app.datasource.foo")
public DataSource fooDataSource() {
return fooDataSourceProperties()
.initializeDataSourceBuilder()
.build();
}
@Bean
@ConfigurationProperties("app.datasource.bar")
public BasicDataSource barDataSource() {
return (BasicDataSource) DataSourceBuilder.create()
.type(BasicDataSource.class)
.build();
}
// end::configuration[]
}
}

@ -0,0 +1,54 @@
/*
* Copyright 2012-2017 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.jdbc;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link BasicDataSourceExample}.
* @author Stephane Nicoll
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "app.datasource.url=jdbc:h2:mem:basic;DB_CLOSE_DELAY=-1")
@Import(BasicDataSourceExample.BasicDataSourceConfiguration.class)
public class BasicDataSourceExampleTests {
@Autowired
private ApplicationContext context;
@Test
public void validateConfiguration() throws SQLException {
assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1);
DataSource dataSource = this.context.getBean(DataSource.class);
assertThat(dataSource.getConnection().getMetaData().getURL())
.isEqualTo("jdbc:h2:mem:basic");
}
}

@ -0,0 +1,62 @@
/*
* Copyright 2012-2017 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.jdbc;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link CompleteTwoDataSourcesExample}.
*
* @author Stephane Nicoll
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Import(CompleteTwoDataSourcesExample.CompleteDataSourcesConfiguration.class)
public class CompleteTwoDataSourcesExampleTests {
@Autowired
private ApplicationContext context;
@Test
public void validateConfiguration() throws SQLException {
assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(2);
DataSource dataSource = this.context.getBean(DataSource.class);
assertThat(this.context.getBean("fooDataSource")).isSameAs(dataSource);
assertThat(dataSource.getConnection().getMetaData().getURL())
.startsWith("jdbc:h2:mem:");
DataSource barDataSource = this.context.getBean("barDataSource",
DataSource.class);
assertThat(barDataSource.getConnection().getMetaData().getURL())
.startsWith("jdbc:h2:mem:");
}
}

@ -0,0 +1,59 @@
/*
* Copyright 2012-2017 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.jdbc;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link SimpleDataSourceExample}.
*
* @author Stephane Nicoll
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {
"app.datasource.url=jdbc:h2:mem:configurable;DB_CLOSE_DELAY=-1",
"app.datasource.maximum-pool-size=42" })
@Import(ConfigurableDataSourceExample.ConfigurableDataSourceConfiguration.class)
public class ConfigurableDataSourceExampleTests {
@Autowired
private ApplicationContext context;
@Test
public void validateConfiguration() throws SQLException {
assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1);
HikariDataSource dataSource = this.context.getBean(HikariDataSource.class);
assertThat(dataSource.getConnection().getMetaData().getURL())
.isEqualTo("jdbc:h2:mem:configurable");
assertThat(dataSource.getMaximumPoolSize()).isEqualTo(42);
}
}

@ -0,0 +1,35 @@
/*
* Copyright 2012-2017 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.jdbc;
import javax.sql.DataSource;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
/**
* A sample {@link SpringBootConfiguration} that only enables the auto-configuration
* for the {@link DataSource}.
*
* @author Stephane Nicoll
*/
@SpringBootConfiguration
@ImportAutoConfiguration(DataSourceAutoConfiguration.class)
class SampleApp {
}

@ -0,0 +1,59 @@
/*
* Copyright 2012-2017 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.jdbc;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test for {@link SimpleDataSourceExample}.
*
* @author Stephane Nicoll
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {
"app.datasource.jdbc-url=jdbc:h2:mem:simple;DB_CLOSE_DELAY=-1",
"app.datasource.maximum-pool-size=42" })
@Import(SimpleDataSourceExample.SimpleDataSourceConfiguration.class)
public class SimpleDataSourceExampleTests {
@Autowired
private ApplicationContext context;
@Test
public void validateConfiguration() throws SQLException {
assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(1);
HikariDataSource dataSource = this.context.getBean(HikariDataSource.class);
assertThat(dataSource.getConnection().getMetaData().getURL())
.isEqualTo("jdbc:h2:mem:simple");
assertThat(dataSource.getMaximumPoolSize()).isEqualTo(42);
}
}

@ -0,0 +1,66 @@
/*
* Copyright 2012-2017 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.jdbc;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SimpleTwoDataSourcesExample}.
*
* @author Stephane Nicoll
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {
"app.datasource.bar.url=jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1",
"app.datasource.bar.max-total=42" })
@Import(SimpleTwoDataSourcesExample.SimpleDataSourcesConfiguration.class)
public class SimpleTwoDataSourcesExampleTests {
@Autowired
private ApplicationContext context;
@Test
public void validateConfiguration() throws SQLException {
assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(2);
DataSource dataSource = this.context.getBean(DataSource.class);
assertThat(this.context.getBean("fooDataSource")).isSameAs(dataSource);
assertThat(dataSource.getConnection().getMetaData().getURL())
.startsWith("jdbc:h2:mem:");
BasicDataSource barDataSource = this.context.getBean("barDataSource",
BasicDataSource.class);
assertThat(barDataSource.getUrl())
.isEqualTo("jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1");
assertThat(barDataSource.getMaxTotal()).isEqualTo(42);
}
}
Loading…
Cancel
Save