Use @Configuration on classes that declare Spring beans. With component scanning active, Spring Boot discovers configuration classes in the main application package and its subpackages, including test-side configurations on the test classpath. section 3.3.3
Choose the configuration scope deliberately when building Spring Boot test contexts:
- Place a regular @Configuration class beneath the application package to include its beans automatically; every @SpringBootTest may then receive those beans. section 3.3.3
- Use @TestConfiguration for test-only beans that should be added explicitly, either by nesting the class in a test or importing it with @Import. section 3.3.3
- Use @SpringBootTest(classes = { ... }) to load selected configuration classes rather than the full application; imported components and transitive dependencies can still expand the context. section 3.3.4
Selective test configuration
A test can declare @SpringBootTest(classes = { ThingConfiguration.class }) to load only ThingConfiguration and its beans. This keeps Spring facilities such as property parsing, validation, and conditional annotations available without loading the production application. Keep configuration classes composable and focused, because missing dependencies prevent the context from starting. section 3.3.4
Listing 3.9 Project file structure for custom configurations
src
├─ main
│ └─ java
│ └─ com
│ └─ example
│ ├─ DemoApplication.java #1
│ ├─ ProductionConfiguration.java
│ └─ ... more production code ...
└─ test
└─ java
└─ com
└─ example
│ ├─ TopLevelConfiguration.java #2
│ ├─ nested
│ │ └─ NestedConfiguration.java #2
│ └─ ... your tests ...
└─ notincluded
└─ ExcludedConfiguration.java #3
Use the project structure to see which configuration classes fall under the main application package and which remain excluded from component scanning. section 3.3.3
