Skip to content

Commit d8d6cb7

Browse files
committed
Improve diagnostics with @Serviceconnection on non-static field
Closes gh-34795
1 parent 2267430 commit d8d6cb7

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/service/connection/ServiceConnectionContextCustomizerFactory.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package org.springframework.boot.test.autoconfigure.service.connection;
1818

1919
import java.lang.reflect.Field;
20+
import java.lang.reflect.Modifier;
2021
import java.util.ArrayList;
2122
import java.util.List;
2223

@@ -62,6 +63,9 @@ private void findSources(Class<?> clazz, List<ContainerConnectionSource<?, ?, ?>
6263

6364
private ContainerConnectionSource<?, ?, ?> createSource(Field field,
6465
MergedAnnotation<ServiceConnection> annotation) {
66+
if (!Modifier.isStatic(field.getModifiers())) {
67+
throw new IllegalStateException("@ServiceConnection field '%s' must be static".formatted(field.getName()));
68+
}
6569
Class<? extends ConnectionDetails> connectionDetailsType = getConnectionDetailsType(annotation);
6670
Object fieldValue = getFieldValue(field);
6771
Assert.isInstanceOf(GenericContainer.class, fieldValue,

spring-boot-project/spring-boot-test-autoconfigure/src/test/java/org/springframework/boot/test/autoconfigure/service/connection/ServiceConnectionContextCustomizerFactoryTests.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import org.springframework.boot.test.autoconfigure.service.connection.ServiceConnectionContextCustomizerFactoryTests.ServiceConnections.NestedClass;
2525

2626
import static org.assertj.core.api.Assertions.assertThat;
27+
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
2728

2829
/**
2930
* Tests for {@link ServiceConnectionContextCustomizerFactory}.
@@ -55,6 +56,13 @@ void whenEnclosingClassHasServiceConnectionsThenCreateReturnsCustomizer() {
5556
assertThat(customizer.getSources()).hasSize(3);
5657
}
5758

59+
@Test
60+
void whenClassHasNonStaticServiceConnectionThenCreateShouldFailWithHelpfulIllegalStateException() {
61+
assertThatIllegalStateException()
62+
.isThrownBy(() -> this.factory.createContextCustomizer(NonStaticServiceConnection.class, null))
63+
.withMessage("@ServiceConnection field 'service' must be static");
64+
}
65+
5866
static class NoServiceConnections {
5967

6068
}
@@ -77,6 +85,13 @@ class NestedClass {
7785

7886
}
7987

88+
static class NonStaticServiceConnection {
89+
90+
@ServiceConnection(TestConnectionDetails.class)
91+
private GenericContainer<?> service = new GenericContainer<>("example");
92+
93+
}
94+
8095
static class TestConnectionDetails implements ConnectionDetails {
8196

8297
}

0 commit comments

Comments
 (0)