在 spring boot 项目中,junit 测试启动类通过 @springboottest 注解指定。该注解默认使用项目主启动类(包含 @springbootapplication 的类)来构建测试上下文。若需自定义配置,可通过 classes 属性显式指定一个或多个配置类,从而控制哪些 bean 被加载以及自动配置的生效范围。

如何指定非主启动类的配置类?
当测试需要隔离特定模块或模拟环境时,可以不在主启动类上运行,而是通过 @SpringBootTest(classes = {ConfigClass.class}) 显式指定配置类。这会导致 Spring 容器仅加载这些类及其依赖的组件,忽略其他自动配置。

import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Service; @Configuration class TestConfig {} @Service class DemoService {} @SpringBootTest(classes = {TestConfig.class, DemoService.class}) public class CustomContextTest { // 测试逻辑 }
上述代码中,classes 参数明确列出了 TestConfig 和 DemoService。运行测试时,Spring 上下文将只包含这两个 Bean,不会扫描其他包下的组件。
如何排除特定自动配置?
如果希望保留主启动类但禁用某些自动配置(如 Web 环境或数据库连接),可以使用 excludeAutoConfiguration 属性。这会告诉 Spring Boot 在初始化上下文时跳过指定的自动配置类,从而改变可用的 Bean 集合。

import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest(excludeAutoConfiguration = {DataSourceAutoConfiguration.class}) public class ExcludeAutoConfigTest { // 测试逻辑 }
在此示例中,DataSourceAutoConfiguration 被排除,因此测试上下文中不会出现数据源相关的 Bean,避免了因缺少数据库配置而导致的启动失败。
指定 classes 后实际加载了哪些 Bean?
当使用 classes 属性指定配置类时,Spring 会处理这些类上的所有注解。例如,若指定的类包含 @ComponentScan,则扫描范围受其限制;若不指定,则默认扫描该类所在包及子包。以下代码验证了这一点:
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(classes = {TestConfig.class, DemoService.class}) public class BeanVerificationTest { @Autowired private DemoService demoService; @Test void contextLoads() { assertThat(demoService).isNotNull(); } }
运行此测试,demoService 会被成功注入,因为它是 classes 列表中显式声明的 Bean。若尝试注入未列出的 Bean,则会抛出 NoSuchBeanDefinitionException,证明上下文确实只加载了指定内容。











