对于最新稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

使用环境配置文件进行上下文配置

Spring 框架对环境和配置文件(即“Bean 定义配置文件”)的概念提供了一流的支持,集成测试可以配置为在各种测试场景中激活特定的 Bean 定义配置文件。这通过使用 @ActiveProfiles 注解标注测试类,并在为测试加载 ApplicationContext 时提供应激活的配置文件列表来实现。spring-doc.cadn.net.cn

您可以将 @ActiveProfiles 与任何 SmartContextLoader SPI 的实现一起使用,但 @ActiveProfiles 不支持与旧版 ContextLoader SPI 的实现一起使用。

考虑两个示例,分别使用 XML 配置和 @Configuration 类:spring-doc.cadn.net.cn

<!-- app-config.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xsi:schemaLocation="...">

	<bean id="transferService"
			class="com.bank.service.internal.DefaultTransferService">
		<constructor-arg ref="accountRepository"/>
		<constructor-arg ref="feePolicy"/>
	</bean>

	<bean id="accountRepository"
			class="com.bank.repository.internal.JdbcAccountRepository">
		<constructor-arg ref="dataSource"/>
	</bean>

	<bean id="feePolicy"
		class="com.bank.service.internal.ZeroFeePolicy"/>

	<beans profile="dev">
		<jdbc:embedded-database id="dataSource">
			<jdbc:script
				location="classpath:com/bank/config/sql/schema.sql"/>
			<jdbc:script
				location="classpath:com/bank/config/sql/test-data.sql"/>
		</jdbc:embedded-database>
	</beans>

	<beans profile="production">
		<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>
	</beans>

	<beans profile="default">
		<jdbc:embedded-database id="dataSource">
			<jdbc:script
				location="classpath:com/bank/config/sql/schema.sql"/>
		</jdbc:embedded-database>
	</beans>

</beans>
@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from "classpath:/app-config.xml"
@ContextConfiguration("/app-config.xml")
@ActiveProfiles("dev")
class TransferServiceTest {

	@Autowired
	TransferService transferService;

	@Test
	void testTransferService() {
		// test the transferService
	}
}
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from "classpath:/app-config.xml"
@ContextConfiguration("/app-config.xml")
@ActiveProfiles("dev")
class TransferServiceTest {

	@Autowired
	lateinit var transferService: TransferService

	@Test
	fun testTransferService() {
		// test the transferService
	}
}

当运行 TransferServiceTest 时,其 ApplicationContext 会从类路径根目录下的 app-config.xml 配置文件中加载。如果您检查 app-config.xml,可以看到 accountRepository Bean 依赖于一个 dataSource Bean。然而,dataSource 并未定义为顶层 Bean。相反,dataSource 被定义了三次:分别在 production 配置文件、dev 配置文件和 default 配置文件中。spring-doc.cadn.net.cn

通过使用 TransferServiceTest 注解 @ActiveProfiles("dev"),我们指示 Spring TestContext 框架加载 ApplicationContext,并将激活的配置文件设置为 {"dev"}。结果会创建一个嵌入式数据库并填充测试数据,同时 accountRepository bean 会被注入一个指向开发环境 DataSource 的引用。这通常正是我们在集成测试中所期望的行为。spring-doc.cadn.net.cn

有时将 Bean 分配给 default(默认)配置文件非常有用。只有在未显式激活其他任何配置文件时,才会包含默认配置文件中的 Bean。你可以利用这一点来定义应用程序在默认状态下使用的“后备”Bean。例如,你可以为 dev(开发)和 production(生产)配置文件显式提供数据源,但在这些配置文件均未激活时,将内存数据源作为默认选项。spring-doc.cadn.net.cn

以下代码示例演示了如何使用 @Configuration 类而非 XML 来实现相同的配置和集成测试:spring-doc.cadn.net.cn

@Configuration
@Profile("dev")
public class StandaloneDataConfig {

	@Bean
	public DataSource dataSource() {
		return new EmbeddedDatabaseBuilder()
			.setType(EmbeddedDatabaseType.HSQL)
			.addScript("classpath:com/bank/config/sql/schema.sql")
			.addScript("classpath:com/bank/config/sql/test-data.sql")
			.build();
	}
}
@Configuration
@Profile("dev")
class StandaloneDataConfig {

	@Bean
	fun dataSource(): DataSource {
		return EmbeddedDatabaseBuilder()
				.setType(EmbeddedDatabaseType.HSQL)
				.addScript("classpath:com/bank/config/sql/schema.sql")
				.addScript("classpath:com/bank/config/sql/test-data.sql")
				.build()
	}
}
@Configuration
@Profile("production")
public class JndiDataConfig {

	@Bean(destroyMethod="")
	public DataSource dataSource() throws Exception {
		Context ctx = new InitialContext();
		return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
	}
}
@Configuration
@Profile("production")
class JndiDataConfig {

	@Bean(destroyMethod = "")
	fun dataSource(): DataSource {
		val ctx = InitialContext()
		return ctx.lookup("java:comp/env/jdbc/datasource") as DataSource
	}
}
@Configuration
@Profile("default")
public class DefaultDataConfig {

	@Bean
	public DataSource dataSource() {
		return new EmbeddedDatabaseBuilder()
			.setType(EmbeddedDatabaseType.HSQL)
			.addScript("classpath:com/bank/config/sql/schema.sql")
			.build();
	}
}
@Configuration
@Profile("default")
class DefaultDataConfig {

	@Bean
	fun dataSource(): DataSource {
		return EmbeddedDatabaseBuilder()
				.setType(EmbeddedDatabaseType.HSQL)
				.addScript("classpath:com/bank/config/sql/schema.sql")
				.build()
	}
}
@Configuration
public class TransferServiceConfig {

	@Autowired DataSource dataSource;

	@Bean
	public TransferService transferService() {
		return new DefaultTransferService(accountRepository(), feePolicy());
	}

	@Bean
	public AccountRepository accountRepository() {
		return new JdbcAccountRepository(dataSource);
	}

	@Bean
	public FeePolicy feePolicy() {
		return new ZeroFeePolicy();
	}
}
@Configuration
class TransferServiceConfig {

	@Autowired
	lateinit var dataSource: DataSource

	@Bean
	fun transferService(): TransferService {
		return DefaultTransferService(accountRepository(), feePolicy())
	}

	@Bean
	fun accountRepository(): AccountRepository {
		return JdbcAccountRepository(dataSource)
	}

	@Bean
	fun feePolicy(): FeePolicy {
		return ZeroFeePolicy()
	}
}
@SpringJUnitConfig({
		TransferServiceConfig.class,
		StandaloneDataConfig.class,
		JndiDataConfig.class,
		DefaultDataConfig.class})
@ActiveProfiles("dev")
class TransferServiceTest {

	@Autowired
	TransferService transferService;

	@Test
	void testTransferService() {
		// test the transferService
	}
}
@SpringJUnitConfig(
		TransferServiceConfig::class,
		StandaloneDataConfig::class,
		JndiDataConfig::class,
		DefaultDataConfig::class)
@ActiveProfiles("dev")
class TransferServiceTest {

	@Autowired
	lateinit var transferService: TransferService

	@Test
	fun testTransferService() {
		// test the transferService
	}
}

在此变体中,我们将 XML 配置拆分成了四个独立的@Configuration类:spring-doc.cadn.net.cn

  • TransferServiceConfig:通过使用 dataSource 注解,以依赖注入的方式获取一个 @Autowiredspring-doc.cadn.net.cn

  • StandaloneDataConfig:为嵌入式数据库定义一个dataSource,适用于开发人员测试。spring-doc.cadn.net.cn

  • JndiDataConfig:在生产环境中定义一个从 JNDI 获取的 dataSourcespring-doc.cadn.net.cn

  • DefaultDataConfig:在没有激活任何配置文件的情况下,为默认的嵌入式数据库定义一个 dataSourcespring-doc.cadn.net.cn

与基于 XML 的配置示例一样,我们仍然使用 TransferServiceTest 注解 @ActiveProfiles("dev"),但这次我们通过 @ContextConfiguration 注解指定了全部四个配置类。测试类本身的代码则完全保持不变。spring-doc.cadn.net.cn

在给定项目中,通常会在多个测试类之间使用同一组配置文件(profiles)。因此,为了避免重复声明 @ActiveProfiles 注解,你可以将其一次性声明在基类上,子类会自动从基类继承 @ActiveProfiles 的配置。在以下示例中,@ActiveProfiles 注解(以及其他注解)已被移到一个抽象超类 @ActiveProfiles 中:spring-doc.cadn.net.cn

自 Spring Framework 5.3 起,测试配置也可以从外部类继承。有关详细信息,请参阅 @Nested 测试类配置
@SpringJUnitConfig({
		TransferServiceConfig.class,
		StandaloneDataConfig.class,
		JndiDataConfig.class,
		DefaultDataConfig.class})
@ActiveProfiles("dev")
abstract class AbstractIntegrationTest {
}
@SpringJUnitConfig(
		TransferServiceConfig::class,
		StandaloneDataConfig::class,
		JndiDataConfig::class,
		DefaultDataConfig::class)
@ActiveProfiles("dev")
abstract class AbstractIntegrationTest {
}
// "dev" profile inherited from superclass
class TransferServiceTest extends AbstractIntegrationTest {

	@Autowired
	TransferService transferService;

	@Test
	void testTransferService() {
		// test the transferService
	}
}
// "dev" profile inherited from superclass
class TransferServiceTest : AbstractIntegrationTest() {

	@Autowired
	lateinit var transferService: TransferService

	@Test
	fun testTransferService() {
		// test the transferService
	}
}

@ActiveProfiles 还支持一个 inheritProfiles 属性,可用于禁用活动配置文件的继承,如下例所示:spring-doc.cadn.net.cn

// "dev" profile overridden with "production"
@ActiveProfiles(profiles = "production", inheritProfiles = false)
class ProductionTransferServiceTest extends AbstractIntegrationTest {
	// test body
}
// "dev" profile overridden with "production"
@ActiveProfiles("production", inheritProfiles = false)
class ProductionTransferServiceTest : AbstractIntegrationTest() {
	// test body
}

此外,有时需要以编程方式而非声明方式解析测试的激活配置文件——例如,基于:spring-doc.cadn.net.cn

要以编程方式解析激活的 Bean 定义配置文件,您可以实现一个自定义的 ActiveProfilesResolver,并通过 resolver 注解的 @ActiveProfiles 属性进行注册。更多信息,请参阅相应的javadoc。 以下示例演示了如何实现并注册一个自定义的 OperatingSystemActiveProfilesResolverspring-doc.cadn.net.cn

// "dev" profile overridden programmatically via a custom resolver
@ActiveProfiles(
		resolver = OperatingSystemActiveProfilesResolver.class,
		inheritProfiles = false)
class TransferServiceTest extends AbstractIntegrationTest {
	// test body
}
// "dev" profile overridden programmatically via a custom resolver
@ActiveProfiles(
		resolver = OperatingSystemActiveProfilesResolver::class,
		inheritProfiles = false)
class TransferServiceTest : AbstractIntegrationTest() {
	// test body
}
public class OperatingSystemActiveProfilesResolver implements ActiveProfilesResolver {

	@Override
	public String[] resolve(Class<?> testClass) {
		String profile = ...;
		// determine the value of profile based on the operating system
		return new String[] {profile};
	}
}
class OperatingSystemActiveProfilesResolver : ActiveProfilesResolver {

	override fun resolve(testClass: Class<*>): Array<String> {
		val profile: String = ...
		// determine the value of profile based on the operating system
		return arrayOf(profile)
	}
}