Add ifPresent utility methods on RuntimeHints

This commit adds a utility method to register a type for reflection if
it is available on the classpath. It also adds a method to register a
resource pattern if a given location is available.

Closes gh-28617
This commit is contained in:
Stephane Nicoll
2022-06-14 14:00:08 +02:00
parent c4e8ffece1
commit d6d4b98780
4 changed files with 73 additions and 0 deletions

View File

@@ -27,6 +27,8 @@ import org.springframework.lang.Nullable;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* Tests for {@link ReflectionHints}.
@@ -45,6 +47,23 @@ class ReflectionHintsTests {
typeWithMemberCategories(String.class, MemberCategory.DECLARED_FIELDS));
}
@Test
void registerTypeIfPresentRegisterExistingClass() {
this.reflectionHints.registerTypeIfPresent(null, String.class.getName(),
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS));
assertThat(this.reflectionHints.typeHints()).singleElement().satisfies(
typeWithMemberCategories(String.class, MemberCategory.DECLARED_FIELDS));
}
@Test
@SuppressWarnings("unchecked")
void registerTypeIfPresentIgnoreMissingClass() {
Consumer<TypeHint.Builder> hintBuilder = mock(Consumer.class);
this.reflectionHints.registerTypeIfPresent(null, "com.example.DoesNotExist", hintBuilder);
assertThat(this.reflectionHints.typeHints()).isEmpty();
verifyNoInteractions(hintBuilder);
}
@Test
void getTypeUsingType() {
this.reflectionHints.registerType(TypeReference.of(String.class),

View File

@@ -26,6 +26,8 @@ import org.junit.jupiter.api.Test;
import org.springframework.aot.hint.ResourceHintsTests.Nested.Inner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* Tests for {@link ResourceHints}.
@@ -91,6 +93,23 @@ class ResourceHintsTests {
List.of("com/example/to-ignore.properties")));
}
@Test
void registerIfPresentRegisterExistingLocation() {
this.resourceHints.registerPatternIfPresent(null, "META-INF/",
resourceHint -> resourceHint.includes("com/example/*.properties"));
assertThat(this.resourceHints.resourcePatterns()).singleElement().satisfies(
patternOf("com/example/*.properties"));
}
@Test
@SuppressWarnings("unchecked")
void registerIfPresentIgnoreMissingLocation() {
Consumer<ResourcePatternHints.Builder> hintBuilder = mock(Consumer.class);
this.resourceHints.registerPatternIfPresent(null, "location/does-not-exist/", hintBuilder);
assertThat(this.resourceHints.resourcePatterns()).isEmpty();
verifyNoInteractions(hintBuilder);
}
@Test
void registerResourceBundle() {
this.resourceHints.registerResourceBundle("com.example.message");