GH-319 - Fix ApplicationModule by package name lookup.

Prior to this commit, the lookup for an ApplicationModule would find modules solely depending on the reference string starting with the base package. That means that a module with base package com.acme.foo, a request for com.acme.foobar would've resulted in a positive match, which of course is wrong.

We now match against either the module's base package or against the reference starting with the base package followed by a dot.
This commit is contained in:
Oliver Drotbohm
2023-10-15 17:29:27 +02:00
parent db1c2b813e
commit cb6d71ba60
3 changed files with 36 additions and 1 deletions

View File

@@ -414,6 +414,24 @@ public class ApplicationModule {
return getType(candidate).isPresent();
}
/**
* Returns whether the {@link ApplicationModule} contains the package with the given name, which means the given
* package is either the module's base package or a sub package of it.
*
* @param packageName must not be {@literal null} or empty.
* @return whether the {@link ApplicationModule} contains the package with the given name.
* @since 1.0.2
*/
boolean containsPackage(String packageName) {
Assert.hasText(packageName, "Package name must not be null or empty!");
var basePackageName = basePackage.getName();
return packageName.equals(basePackageName)
|| packageName.startsWith(basePackageName + ".");
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)

View File

@@ -326,10 +326,16 @@ public class ApplicationModules implements Iterable<ApplicationModule> {
return getModuleByType(candidate.getName());
}
/**
* Returns the {@link ApplicationModule} containing the given package.
*
* @param name must not be {@literal null} or empty.
* @return will never be {@literal null}.
*/
public Optional<ApplicationModule> getModuleForPackage(String name) {
return modules.values().stream() //
.filter(it -> name.startsWith(it.getBasePackage().getName())) //
.filter(it -> it.containsPackage(name)) //
.findFirst();
}

View File

@@ -16,11 +16,13 @@
package org.springframework.modulith.core;
import static org.assertj.core.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import javax.sql.DataSource;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
@@ -83,4 +85,13 @@ class ModuleUnitTest {
.<Class<?>> extracting(JavaClass::reflect)
.containsExactly(SampleAggregate.class);
}
@Test // GH-319
void containsPackage() {
assertThat(module.containsPackage(packageName)).isTrue();
assertThat(module.containsPackage(packageName + ".foo")).isTrue();
assertThat(module.containsPackage(packageName + "foo")).isFalse();
}
}