Compare commits

..
2 Commits
8 changed files with 2 additions and 161 deletions
@@ -11,7 +11,7 @@ GET /books/99 -> 404
POST /books -> 201
{"id":3,"title":"Clean Code","author":"Robert Martin","pages":464}
POST /books -> 400
{"timestamp":"2026-10-21T16:43:19.747Z","status":400,"error":"Bad Request","path":"/books"}
{"timestamp":"2026-10-21T16:33:04.625Z","status":400,"error":"Bad Request","path":"/books"}
--- byfeature ---
GET /books -> 200
@@ -23,7 +23,7 @@ GET /books/99 -> 404
POST /books -> 201
{"id":3,"title":"Clean Code","author":"Robert Martin","pages":464}
POST /books -> 400
{"timestamp":"2026-10-21T16:43:20.250Z","status":400,"error":"Bad Request","path":"/books"}
{"timestamp":"2026-10-21T16:33:05.081Z","status":400,"error":"Bad Request","path":"/books"}
POST /loans -> 201
{"id":1,"bookId":2,"bookTitle":"Java Concurrency in Practice","member":"Asha"}
POST /loans -> 404
@@ -1,10 +0,0 @@
# The controller is found only if it is in or below the @SpringBootApplication class's package
--- app class in scan.broken.app, controller in scan.broken.web (a sibling) ---
GET /hello -> 404
HelloController registered as a bean: false
--- app class in scan.fixed, controller in scan.fixed.web (below it) ---
GET /hello -> 200
HelloController registered as a bean: true
@@ -1,14 +0,0 @@
# A @SpringBootApplication class in the default package (no package statement)
source compiled:
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DefaultPackageApp {
}
--- what Spring Boot logged about the default package ---
WARNING ** : Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.
--- result ---
context FAILED to start: BeanDefinitionStoreException / root cause ConflictingBeanDefinitionException: Annotation-specified bean name 'bookController' for bean class [com.ankurm.structure.bylayer.controller.BookController] conflicts with existing, non-compatible bean definition of same name and class [com.ankurm.structure.byfeature.book.BookController]
@@ -1,8 +0,0 @@
package com.ankurm.structure.scan.broken.app;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/** Scans com.ankurm.structure.scan.broken.app and below. The controller lives in a sibling package, so it is never found. */
@SpringBootApplication
public class BrokenApp {
}
@@ -1,12 +0,0 @@
package com.ankurm.structure.scan.broken.web;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class HelloController {
@GetMapping("/hello")
String hello() {
return "hello";
}
}
@@ -1,8 +0,0 @@
package com.ankurm.structure.scan.fixed;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/** Scans com.ankurm.structure.scan.fixed and everything below it, including web/. */
@SpringBootApplication
public class FixedApp {
}
@@ -1,12 +0,0 @@
package com.ankurm.structure.scan.fixed.web;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class HelloController {
@GetMapping("/hello")
String hello() {
return "hello";
}
}
@@ -1,95 +0,0 @@
package com.ankurm.structure;
import com.ankurm.structure.scan.broken.app.BrokenApp;
import com.ankurm.structure.scan.fixed.FixedApp;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.ConfigurableApplicationContext;
import javax.tools.*;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/** The two ways a project layout silently breaks component scanning. */
@ExtendWith(OutputCaptureExtension.class)
class ScanTrapTests {
@Test
void appClassInTheWrongPackage() throws Exception {
HttpClient http = HttpClient.newHttpClient();
try (Transcript t = new Transcript("05-scan-starts-at-the-app-class.txt",
"The controller is found only if it is in or below the @SpringBootApplication class's package")) {
for (var c : List.of(
new Object[]{"broken", BrokenApp.class, "app class in scan.broken.app, controller in scan.broken.web (a sibling)"},
new Object[]{"fixed", FixedApp.class, "app class in scan.fixed, controller in scan.fixed.web (below it)"})) {
try (ConfigurableApplicationContext ctx = new SpringApplicationBuilder((Class<?>) c[1])
.properties("server.port=0", "spring.main.banner-mode=off", "logging.level.root=WARN").run()) {
String base = "http://localhost:" + ctx.getEnvironment().getProperty("local.server.port");
HttpResponse<String> r = http.send(HttpRequest.newBuilder(URI.create(base + "/hello")).GET().build(),
HttpResponse.BodyHandlers.ofString());
t.section((String) c[2]);
t.line("GET /hello -> %d", r.statusCode());
t.line("HelloController registered as a bean: %s", ctx.getBeanNamesForType(Object.class).length > 0
&& java.util.Arrays.stream(ctx.getBeanDefinitionNames()).anyMatch(n -> n.equals("helloController")));
if (c[0].equals("broken")) assertThat(r.statusCode()).isEqualTo(404);
else assertThat(r.statusCode()).isEqualTo(200);
}
}
}
}
@Test
void appClassInTheDefaultPackage(CapturedOutput output) throws Exception {
String source = "import org.springframework.boot.autoconfigure.SpringBootApplication;\n"
+ "@SpringBootApplication\n"
+ "public class DefaultPackageApp {\n"
+ "}\n";
Path out = Files.createTempDirectory("defaultpkg");
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
JavaFileObject file = new SimpleJavaFileObject(URI.create("string:///DefaultPackageApp.java"), JavaFileObject.Kind.SOURCE) {
@Override public CharSequence getCharContent(boolean ignore) { return source; }
};
boolean compiled = javac.getTask(null, null, null,
List.of("-proc:none", "-d", out.toString(), "-classpath", System.getProperty("java.class.path")), null, List.of(file)).call();
assertThat(compiled).isTrue();
try (Transcript t = new Transcript("06-default-package.txt", "A @SpringBootApplication class in the default package (no package statement)")) {
t.line("source compiled:");
for (String l : source.split("\n")) t.line(" %s", l);
t.blank();
Class<?> app;
try (URLClassLoader cl = new URLClassLoader(new URL[]{out.toUri().toURL()}, getClass().getClassLoader())) {
app = Class.forName("DefaultPackageApp", true, cl);
String result;
try (ConfigurableApplicationContext ctx = new SpringApplicationBuilder(app)
.web(WebApplicationType.NONE).properties("spring.main.banner-mode=off").run()) {
result = "context started with " + ctx.getBeanDefinitionCount() + " bean definitions";
} catch (Throwable e) {
Throwable root = e;
while (root.getCause() != null) root = root.getCause();
result = "context FAILED to start: " + e.getClass().getSimpleName() + " / root cause "
+ root.getClass().getSimpleName() + ": " + String.valueOf(root.getMessage()).lines().findFirst().orElse("");
}
t.section("what Spring Boot logged about the default package");
output.getAll().lines().filter(l -> l.contains("default package") || l.contains("WARNING"))
.map(l -> l.replaceFirst("^\\S+\\s+", "")).forEach(t::line);
t.section("result");
t.line(result);
}
assertThat(output.getAll()).contains("default package");
}
}
}