Skip to content


Folders and files

Last commit message
Last commit date

Latest commit



21 Commits

Repository files navigation

Spring Dynamic Property

Build Status badge

Tools to define a dynamic property in Spring Boot integration tests.

How to set a property value in tests by the standard spring mechanics

In the Spring Framework we have an annotation TestPropertySource which allows define a final property value:

@TestPropertySource(properties = "my.variable=12345")
class FinalPropertyValueTest {

	private String variable;

	void testVariableValue() {

On this way we have a small limitation - we cannot define a dynamic value of properties in this annotation, even use of a static method not allowed here.

How to define a dynamic value of properties in tests

spring-dynamic-property supports an ability to define a dynamic value of properties and declare static property provider methods in your test class.

All that you need to use the spring-dynamic-property is the next dependency:


Let’s look at the simple example of using a dynamic value in properties:

Simple example

class SimpleTest {

	private static TestPropertyValues props() {
		return TestPropertyValues
				.of("variable=" + (int) Math.sqrt(64));

	private int variable;

	void testSqrt() {

Example with the using of TestContainers

A most primary case to use dynamic properties is a TestContainers initialization in your spring-boot applications.

Let’s consider an example of initialization standard spring-boot properties after start Redis test container:

class RedisTestcontainersTest {

    private static final Integer REDIS_PORT = 6379;

    private static GenericContainer redis = new GenericContainer("redis:latest")

    private static TestPropertyValues props() {
        return TestPropertyValues.of("" + redis.getContainerIpAddress(),
                                     "spring.redis.port=" + redis.getMappedPort(REDIS_PORT));

    private RedisTemplate redisTemplate;

    void readWriteValueByRedisTemplate() {
        String key = "test";
        String value = "sabracadabra";
        // Act
        redisTemplate.opsForValue().set(key, value);
        // Assert

Include dynamic property in meta-annotations

If you need to make you own annotation with dynamic property declaration then you can specify a file with @DynamicProperty methods by the using of @IncludeDynamicProperty annotation as you can see in the example below:

public @interface AnnotationWithDynamicProperty {


the file with dynamic properties:

public class DynamicPropertyHolder {

    private static TestPropertyValues property(){
        return TestPropertyValues.of("key=12345");

and now you can use this annotation in your tests to set this property:

class MetaAnnotationTest {

    private String key;

    void checkPropertyValueInjectInAnnotation() {


Tools to define a dynamic property in Spring Boot integration tests.