question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Spring autoconfigure JDBC pool with Hikari in tests that refreshes context

See original GitHub issue

Affects: Spring boot (with dependencies) 2.7.0


Hello there, I have found quite a strange behaviour in tests (and possibly production code) when using Spring boot together with a connection pool such as Hikari.

When something in my test refreshes the Spring context, (in my case, I’m using mockserver-spring-test-listener), the previous connection pool / datasource is not closed/discarded Instead, Spring re-initializes my beans, (DataSource being one of them), resulting in a bunch of idle pools.

I hadn’t realized this until recently, when my test-db complained that it was out of connections (psql: FATAL: sorry, too many clients already)

My application-test.yaml:

spring:
  datasource:
    validationQuery: SELECT 1
    url: "jdbc:postgresql://localhost:52380/test?user=test&password=test"
    hikari:
      maximum-pool-size: 5

server:
  port: 5000

My test-enabling annotation:

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@MockServerTest(value = {
    "myapp.service1.url=http://localhost:${mockServerPort}",
    "myapp.service2.url=http://localhost:${mockServerPort}",
})
@SpringBootTest(webEnvironment = RANDOM_PORT)
@ActiveProfiles({"test", "test_local"})
public @interface MyTestEnv {
}

My test classes:

@MyTestEnv
class TestClass {

    @Autowired
    private DataSource dataSource;

    private MockServerClient mockServerClient;

    @Test
    void testOne() throws Exception {
        try(var c = dataSource.getConnection()){
	    System.out.println("TestClass output: " + dataSource.getClass());
	}
    }
}

And a secondary test class, such as:

@MyTestEnv
class TestClassTwo {

    @Autowired
    private DataSource dataSource;

    private MockServerClient mockServerClient;

    @Test
    void testTwo() throws Exception {
        try(var c = dataSource.getConnection()){
	    System.out.println("TestClass output: " + dataSource.getClass());
	}
    }
}

This results in the following output when running tests:

Maven/Test output
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ demo ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.demo.TestClassTwo
14:15:31.986 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
14:15:31.989 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
14:15:32.004 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.example.demo.TestClassTwo] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
14:15:32.009 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.example.demo.TestClassTwo], using SpringBootContextLoader
14:15:32.010 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.demo.TestClassTwo]: class path resource [com/example/demo/TestClassTwo-context.xml] does not exist
14:15:32.010 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.demo.TestClassTwo]: class path resource [com/example/demo/TestClassTwoContext.groovy] does not exist
14:15:32.010 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.example.demo.TestClassTwo]: no resource found for suffixes {-context.xml, Context.groovy}.
14:15:32.011 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.example.demo.TestClassTwo]: TestClassTwo does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
14:15:32.057 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [/Users/robin/projects/spring-boot-mvp/target/classes/com/example/demo/DemoApplication.class]
14:15:32.057 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.example.demo.DemoApplication for test class com.example.demo.TestClassTwo
14:15:32.091 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.example.demo.TestClassTwo]: using defaults.
14:15:32.092 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener, org.mockserver.springtest.MockServerTestExecutionListener]
14:15:32.099 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@5ddf0d24, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@363a52f, org.springframework.test.context.event.ApplicationEventsTestExecutionListener@60856961, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@2fd953a6, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@a4add54, org.springframework.test.context.support.DirtiesContextTestExecutionListener@141e5bef, org.springframework.test.context.transaction.TransactionalTestExecutionListener@5f9be66c, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@3abada5a, org.springframework.test.context.event.EventPublishingTestExecutionListener@66c61024, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@61fe30, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@c9d0d6, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@6ccdb29f, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@3adcc812, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@35432107, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@7b420819, org.mockserver.springtest.MockServerTestExecutionListener@7a1a14a4]
14:15:32.100 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@39de3d36 testClass = TestClassTwo, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@6ce86ce1 testClass = TestClassTwo, locations = '{}', classes = '{class com.example.demo.DemoApplication}', contextInitializerClasses = '[]', activeProfiles = '{test, test_local}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=0}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@e1de817, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@13b13b5d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@3246fb96, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@65f095f8, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@120f102b, org.mockserver.springtest.MockServerPropertyCustomizer@383bfa16, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@9660f4e], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> false]], class annotated with @DirtiesContext [false] with mode [null].
14:15:32.105 [main] DEBUG org.springframework.test.context.support.DependencyInjectionTestExecutionListener - Performing dependency injection for test context [[DefaultTestContext@39de3d36 testClass = TestClassTwo, testInstance = com.example.demo.TestClassTwo@8c3619e, testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@6ce86ce1 testClass = TestClassTwo, locations = '{}', classes = '{class com.example.demo.DemoApplication}', contextInitializerClasses = '[]', activeProfiles = '{test, test_local}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=0}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@e1de817, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@13b13b5d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@3246fb96, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@65f095f8, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@120f102b, org.mockserver.springtest.MockServerPropertyCustomizer@383bfa16, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@9660f4e], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> false, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]].

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.0)

2022-06-20 14:15:32.225  INFO 27321 --- [           main] com.example.demo.TestClassTwo            : Starting TestClassTwo using Java 18.0.1.1 on Robins-MacBook-Pro-2.local with PID 27321 (started by robin in /Users/robin/projects/spring-boot-mvp)
2022-06-20 14:15:32.225  INFO 27321 --- [           main] com.example.demo.TestClassTwo            : The following 2 profiles are active: "test", "test_local"
2022-06-20 14:15:32.626  INFO 27321 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 0 (http)
2022-06-20 14:15:32.630  INFO 27321 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-06-20 14:15:32.630  INFO 27321 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.63]
2022-06-20 14:15:32.676  INFO 27321 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-06-20 14:15:32.676  INFO 27321 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 442 ms
2022-06-20 14:15:33.005  INFO 27321 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 55817 (http) with context path ''
2022-06-20 14:15:33.012  INFO 27321 --- [           main] com.example.demo.TestClassTwo            : Started TestClassTwo in 0.9 seconds (JVM running for 1.243)
2022-06-20 14:15:33.117  INFO 27321 --- [erver-EventLog0] org.mockserver.log.MockServerEventLog    : 4103 started on port: 4103
2022-06-20 14:15:33.273  INFO 27321 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-06-20 14:15:33.329  INFO 27321 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
TestClass output: class com.zaxxer.hikari.HikariDataSource
2022-06-20 14:15:33.432  INFO 27321 --- [erver-EventLog0] org.mockserver.log.MockServerEventLog    : 4103 resetting all expectations and request logs
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.487 s - in com.example.demo.TestClassTwo
[INFO] Running com.example.demo.TestClass
2022-06-20 14:15:33.442  INFO 27321 --- [           main] .b.t.c.SpringBootTestContextBootstrapper : Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.example.demo.TestClass], using SpringBootContextLoader
2022-06-20 14:15:33.442  INFO 27321 --- [           main] o.s.t.c.support.AbstractContextLoader    : Could not detect default resource locations for test class [com.example.demo.TestClass]: no resource found for suffixes {-context.xml, Context.groovy}.
2022-06-20 14:15:33.442  INFO 27321 --- [           main] t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default configuration classes for test class [com.example.demo.TestClass]: TestClass does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
2022-06-20 14:15:33.443  INFO 27321 --- [           main] .b.t.c.SpringBootTestContextBootstrapper : Found @SpringBootConfiguration com.example.demo.DemoApplication for test class com.example.demo.TestClass
2022-06-20 14:15:33.443  INFO 27321 --- [           main] .b.t.c.SpringBootTestContextBootstrapper : Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener, org.mockserver.springtest.MockServerTestExecutionListener]
2022-06-20 14:15:33.443  INFO 27321 --- [           main] .b.t.c.SpringBootTestContextBootstrapper : Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@74a5bef0, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@68c4a860, org.springframework.test.context.event.ApplicationEventsTestExecutionListener@570ed9c, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@93f15f6, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@5034681f, org.springframework.test.context.support.DirtiesContextTestExecutionListener@1dfe5dd1, org.springframework.test.context.transaction.TransactionalTestExecutionListener@1fe05fff, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@6e017950, org.springframework.test.context.event.EventPublishingTestExecutionListener@1d06801f, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@727956bb, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@6ffbf0ac, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@ad5cffa, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@237aa0c7, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@1b8ee69d, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@2b400bd0, org.mockserver.springtest.MockServerTestExecutionListener@fceab5d]

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.0)

2022-06-20 14:15:33.453  INFO 27321 --- [           main] com.example.demo.TestClass               : Starting TestClass using Java 18.0.1.1 on Robins-MacBook-Pro-2.local with PID 27321 (started by robin in /Users/robin/projects/spring-boot-mvp)
2022-06-20 14:15:33.453  INFO 27321 --- [           main] com.example.demo.TestClass               : The following 2 profiles are active: "test", "test_local"
2022-06-20 14:15:33.534  INFO 27321 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 0 (http)
2022-06-20 14:15:33 5.11.2 INFO Initializing ProtocolHandler ["http-nio-auto-2"] 
2022-06-20 14:15:33 5.11.2 INFO Starting service [Tomcat] 
2022-06-20 14:15:33 5.11.2 INFO Starting Servlet engine: [Apache Tomcat/9.0.63] 
2022-06-20 14:15:33 5.11.2 INFO Initializing Spring embedded WebApplicationContext 
2022-06-20 14:15:33.546  INFO 27321 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 92 ms
2022-06-20 14:15:33 5.11.2 INFO Starting ProtocolHandler ["http-nio-auto-2"] 
2022-06-20 14:15:33.652  INFO 27321 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 55832 (http) with context path ''
2022-06-20 14:15:33.653  INFO 27321 --- [           main] com.example.demo.TestClass               : Started TestClass in 0.209 seconds (JVM running for 1.884)
2022-06-20 14:15:33.655  INFO 27321 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Starting...
2022-06-20 14:15:33.676  INFO 27321 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Start completed.
TestClass output: class com.zaxxer.hikari.HikariDataSource
2022-06-20 14:15:33.705  INFO 27321 --- [erver-EventLog0] org.mockserver.log.MockServerEventLog    : 4103 resetting all expectations and request logs
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.257 s - in com.example.demo.TestClass
2022-06-20 14:15:33.711  INFO 27321 --- [erver-EventLog0] org.mockserver.log.MockServerEventLog    : stopped for port: 4103
2022-06-20 14:15:33.716  INFO 27321 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2022-06-20 14:15:33.717  INFO 27321 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2022-06-20 14:15:33.720  INFO 27321 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Shutdown initiated...
2022-06-20 14:15:33.720  INFO 27321 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Shutdown completed.

As you can see, anytime Spring re-initalizes, it creates a new pool:

com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
... refresh
com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Starting...

But not until all tests have ran, does it shutdown each pool. If I would have had 20 of these test classes, I would’ve used up all 100 connections postgres ships with by default. (20 x 5 (per pool)

Last but not least, here’s my

My pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.0</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>18</java.version>
	</properties>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-dependencies</artifactId>
				<version>2.7.0</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
		</dependency>

		<!-- Others -->
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
		</dependency>

		<!-- Test dependencies -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mock-server</groupId>
			<artifactId>mockserver-spring-test-listener</artifactId>
			<version>5.11.2</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

I’ve tried solving in in various different ways;

  • Creating wrapper beans that calls close on the HikariDataSource (with a @PreDestroy) (Didn’t work, bean is not destroyed)
  • Listening to different application events, in order to clean up the old DSs… (No suitable event to listen to, would need a PreApplicationContextRefreshed event or something similar)
  • Setting the time to live on each connection very low (but that’s kind of a hack… and the lowest allowed is 30s)

Any help would be very appreciated!

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
wilkinsonacommented, Jun 20, 2022

I suspect you are hitting https://github.com/mock-server/mockserver/issues/1044. It’s been fixed by https://github.com/mock-server/mockserver/pull/1045 in 5.12.0. Please try upgrading your MockServer dependency and let us know how it goes.

1reaction
wilkinsonacommented, Jun 22, 2022

It’s described in the docs that I linked to earlier:

The size of the context cache is bounded with a default maximum size of 32. Whenever the maximum size is reached, a least recently used (LRU) eviction policy is used to evict and close stale contexts. You can configure the maximum size from the command line or a build script by setting a JVM system property named spring.test.context.cache.maxSize. As an alternative, you can set the same property via the SpringProperties mechanism.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Spring autoconfigure JDBC pool with Hikari in tests that ...
When something in my test refreshes the Spring context, (in my case, I'm using mockserver-spring-test-listener ), the previous connection ...
Read more >
Configuring a Hikari Connection Pool with Spring Boot
The discovery algorithm that automatically determines a DataSource implementation now prefers Hikari over TomcatJDBC (see the reference manual).
Read more >
Spring Boot Application gets stuck on "Hikari-Pool-1 - Starting..."
I'm trying to run Spring Boot application connected to PostgreSQL database. However, when it comes to Hikari connection pool initializing, ...
Read more >
Example fails to start with HikariDataSource related error #12
HikariConfig : Failed to load driver class com.mysql.jdbc. ... Exception encountered during context initialization - cancelling refresh ...
Read more >
“How-to” Guides - Spring
Look for classes called *AutoConfiguration and read their sources. ... Driver spring.datasource.url=jdbc:mysql://localhost/test server.port= ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found