> For the complete documentation index, see [llms.txt](https://www.pranaypourkar.co.in/the-programmers-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.pranaypourkar.co.in/the-programmers-guide/software-testing/java-test-framework/spring-test/dynamic-property-registration.md).

# Dynamic Property Registration

Spring Boot provides ways to register properties dynamically within the application context. This helps to:

* **Enhance Integration Testing:** Particularly useful for integration tests utilizing Testcontainers, we can set properties based on container details dynamically.
* **Flexibility:** Retrieve property values from external resources like databases or environment variables during runtime.
* **Implement Custom Logic:** Design custom logic for determining property values, enabling complex test configurations or dynamic behavior adjustments.

Two key annotations for dynamic property registration are:

1. `@DynamicPropertySource` : Used to register properties dynamically within the test class, particularly useful for integration tests. It is a **method-level** annotation.

**Example:**

Create Integration test file ***SampleIT.java***

```java
package org.example;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;

import java.util.function.Supplier;

@Slf4j
@SpringBootTest(classes = Application.class)
class SampleIT {

    @Value("${service.client.url}")
    private String testServiceUrlProperty;

    @DynamicPropertySource
    static void properties(DynamicPropertyRegistry registry) {
        // Retrieve the property value dynamically (e.g., from a database or testcontainer)
        String serverHost = "testcontainerHost";
        int serverPort = 1080;
        String path = "auth";

        Supplier<Object> serviceUrl = () -> String.format("http://%s:%d/%s", serverHost, serverPort, path);

        registry.add("service.client.url", serviceUrl);
    }

    @Test
    void testDynamicProperties() {
        log.info("testServiceUrlProperty: {}", testServiceUrlProperty);
        Assertions.assertEquals("http://testcontainerHost:1080/auth", testServiceUrlProperty);
    }
}
```

<figure><img src="https://3632859567-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPd6ktrA5pPLsZJktj2fm%2Fuploads%2Fgit-blob-83cdc01800074017bcc2dffe1b3f6771d5539757%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Make sure to include below dependencies and failsafe plugin

{% code title="pom.xml" %}

```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <scope>test</scope>
</dependency>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
        <version>2.22.2</version>
        <executions>
            <execution>
                <goals>
                    <goal>integration-test</goal>
                    <goal>verify</goal>
                </goals>
            </execution>
        </executions>
</plugin>
```

{% endcode %}
{% endhint %}

2. `@TestPropertySource` : Not strictly for dynamic properties, but rather for overriding application properties specifically within the integration tests or for creating new static properties. It is a **class-level** annotation.

```java
package org.example;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;

@Slf4j
@SpringBootTest(classes = Application.class)
@TestPropertySource(properties = {
        "spring.datasource.url=jdbc:h2:mem:testdb",
        "spring.jpa.hibernate.ddl-auto=create-drop"
})
class SampleIT {

    @Value("${spring.datasource.url}")
    private String springDatasourceUrl;
    @Value("${spring.jpa.hibernate.ddl-auto}")
    private String springJpaProperty;

    @Test
    void testPropertySource() {
        log.info("springDatasourceUrl: {}", springDatasourceUrl);
        log.info("springJpaProperty: {}", springJpaProperty);
        Assertions.assertEquals("jdbc:h2:mem:testdb", springDatasourceUrl);
        Assertions.assertEquals("create-drop", springJpaProperty);
    }
}
```

<figure><img src="https://3632859567-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPd6ktrA5pPLsZJktj2fm%2Fuploads%2Fgit-blob-22cbf2e00c7eeb8c311f25aca7843f4e22b15cfb%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Both `@TestPropertySource` and `@DynamicPropertySource` are processed **before** the Spring application context is loaded for the integration test. This ensures that the properties defined in these annotations are available for use by the test beans and components.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://www.pranaypourkar.co.in/the-programmers-guide/software-testing/java-test-framework/spring-test/dynamic-property-registration.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
