使用环境 profiles 配置上下文

Spring Framework 对环境和 profiles(也称为“bean 定义 profiles”)的概念提供了头等支持,并且可以将集成测试配置为激活特定的 bean 定义 profiles 以适应各种测试场景。这可以通过使用 @ActiveProfiles 注解标注测试类,并提供在为测试加载 ApplicationContext 时应激活的 profiles 列表来实现。

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

考虑使用 XML 配置和 @Configuration 类的两个示例

<!-- 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>
  • Java

  • Kotlin

@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 profile 中,在 dev profile 中,以及在 default profile 中。

通过使用 @ActiveProfiles("dev") 标注 TransferServiceTest,我们指示 Spring TestContext Framework 加载 ApplicationContext,并将激活的 profiles 设置为 {"dev"}。结果是,创建并填充了测试数据的嵌入式数据库,并且 accountRepository bean 被连接到开发 DataSource。这很可能就是我们在集成测试中想要的。

有时将 bean 分配给 default profile 会很有用。仅当没有其他 profile 被特别激活时,default profile 中的 bean 才会包含在内。您可以使用此功能来定义在应用程序默认状态下使用的“备用”bean。例如,您可以为 devproduction profiles 显式提供一个数据源,但在两者都未激活时,将内存数据库源定义为 default 数据源。

以下代码清单演示了如何使用 @Configuration 类而不是 XML 来实现相同的配置和集成测试

  • Java

  • Kotlin

@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()
	}
}
  • Java

  • Kotlin

@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
	}
}
  • Java

  • Kotlin

@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()
	}
}
  • Java

  • Kotlin

@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()
	}
}
  • Java

  • Kotlin

@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

  • TransferServiceConfig:使用 @Autowired 通过依赖注入获取 dataSource

  • StandaloneDataConfig:为适用于开发者测试的嵌入式数据库定义 dataSource

  • JndiDataConfig:定义在生产环境中从 JNDI 获取的 dataSource

  • DefaultDataConfig:定义 default 嵌入式数据库的 dataSource,以防没有 profile 被激活。

与基于 XML 的配置示例一样,我们仍然使用 @ActiveProfiles("dev") 注解 TransferServiceTest,但这次我们使用 @ContextConfiguration 注解指定所有四个配置类。测试类本身的主体保持完全不变。

在给定的项目中,通常在多个测试类中使用同一组 profiles。因此,为避免重复声明 @ActiveProfiles 注解,您可以在基类上声明一次 @ActiveProfiles,子类会自动从基类继承 @ActiveProfiles 配置。在以下示例中,@ActiveProfiles(以及其他注解)的声明已移至抽象超类 AbstractIntegrationTest

测试配置也可以从外围类继承。有关详细信息,请参阅@Nested 测试类配置
  • Java

  • Kotlin

@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 {
}
  • Java

  • Kotlin

// "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 属性,可用于禁用活动 profiles 的继承,如下例所示

  • Java

  • Kotlin

// "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
}

此外,有时需要以编程方式而不是声明式方式解析测试的活动 profiles,例如,根据

  • 当前操作系统。

  • 测试是否在持续集成构建服务器上运行。

  • 某些环境变量的存在。

  • 自定义类级别注解的存在。

  • 其他考量因素。

要以编程方式解析活动 bean 定义 profiles,您可以实现自定义的 ActiveProfilesResolver 并使用 @ActiveProfilesresolver 属性进行注册。有关详细信息,请参阅相应的javadoc。以下示例演示了如何实现和注册自定义的 OperatingSystemActiveProfilesResolver

  • Java

  • Kotlin

// "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
}
  • Java

  • Kotlin

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)
	}
}