Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

How would you add a custom PropertySource, for example values read from an internal secrets service, before the application context is created?

We implement an EnvironmentPostProcessor that fetches the values and adds them as a PropertySource with environment.getPropertySources().addFirst(...) or addAfter(...), and register it in META-INF/spring.factories under the EnvironmentPostProcessor key; the interface moved package in Spring Boot 4, so check your version. The more modern alternative is a ConfigDataLocationResolver and ConfigDataLoader used through spring.config.import. Either way, we decide explicitly what happens when the secrets service is down, fail fast or an optional import, and we never log the secret values.

Why this question is asked

Secrets often live in an internal service rather than in files, and the application needs them before any bean is created, because datasource and client configuration depends on them. That rules out an ordinary bean that fetches them at startup: by the time it runs, the beans that need the values may already be configured. Interviewers ask this to see whether we know the hooks Spring Boot offers before the context exists and how to use them safely. In this answer, we will recap when the Environment is prepared, build an EnvironmentPostProcessor step by step, look at the ConfigData alternative, and then handle failures and secrecy.

1A Quick Recap of When the Environment Is Prepared

When SpringApplication.run starts, it first creates and prepares the Environment: it adds the command-line arguments, system properties and environment variables, then loads the application files and any spring.config.import locations. Only after that does it create the application context and start defining beans. Everything that influences bean definitions or conditions, such as @ConditionalOnProperty, must therefore be in the Environment by the end of that first phase.

Spring Boot offers two extension points inside this phase. An EnvironmentPostProcessor is called with the Environment and can change it freely. The ConfigData API lets us teach Boot a new kind of location, such as secrets://payments, that it then loads like a file.

Step throughStartup order that matters here
  1. Create the Environmentcommand line, system properties, environment variables
  2. Load config dataapplication files and spring.config.import locations
  3. Run EnvironmentPostProcessorsours adds the secrets source
  4. Create the application contextconditions and beans see the secrets

4 steps in order. Play them, or step through them one at a time.

2Writing an EnvironmentPostProcessor

Our post processor reads the address of the secrets service from the Environment, which works because we order it after the config data processor that loads application.yml. It fetches the secrets and adds them as a MapPropertySource, a PropertySource backed by a Map.

Java
public class SecretsEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
private final Log log;
public SecretsEnvironmentPostProcessor(DeferredLogFactory logFactory) {
this.log = logFactory.getLog(SecretsEnvironmentPostProcessor.class); // logging is not set up yet
}
@Override
public void postProcessEnvironment(ConfigurableEnvironment env, SpringApplication app) {
String url = env.getProperty("secrets.url"); // from application.yml
if (url == null) return; // feature not configured
Map<String, Object> secrets = new SecretsClient(url).fetch("payments");
MapPropertySource source = new MapPropertySource("internal-secrets", secrets);
env.getPropertySources().addAfter(
CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME, source); // below --args, above the rest
log.info("Loaded " + secrets.size() + " secrets from " + url); // count only, never values
}
@Override
public int getOrder() {
return ConfigDataEnvironmentPostProcessor.ORDER + 1; // run after application.yml is loaded
}
}

Notice the choice between addFirst and addAfter. addFirst puts the secrets above everything, even command-line arguments, which means nobody can override a secret for a local run. addAfter the command-line source keeps the usual rule that a command-line argument wins. If the command-line source is absent, addAfter throws, so a real implementation checks contains() first and falls back to addFirst.

The constructor takes a DeferredLogFactory because logging is not configured yet when post processors run; Boot replays the deferred messages once logging is ready. Boot can pass that and a ConfigurableBootstrapContext to the constructor.

3Registering It

Environment post processors are not beans, because no context exists yet. Spring Boot finds them through META-INF/spring.factories, keyed by the fully qualified name of the interface.

Text
# src/main/resources/META-INF/spring.factories (Spring Boot 3.x)
org.springframework.boot.env.EnvironmentPostProcessor=\
com.example.secrets.SecretsEnvironmentPostProcessor

In Spring Boot 4 the EnvironmentPostProcessor interface moved to a different package, with the old one deprecated, so the key in spring.factories must match the interface our class implements. Check the version in use and its migration notes rather than copying a key from an old blog post. A typo in this file fails silently: the class is simply never called, so a test that starts the application and asserts a secret is present is worth adding.

4The ConfigData Alternative

Since Spring Boot 2.4, the ConfigData API is the intended way to add new configuration locations. We write a ConfigDataLocationResolver, which recognises locations with our prefix and turns them into resources, and a ConfigDataLoader, which loads a resource into PropertySources. Both are registered in spring.factories under their own interface names. Users then import the location in application.yml.

Java
# application.yml
spring:
config:
import: "optional:secrets://payments" # optional: start even if the service is unreachable
class SecretsLocationResolver implements ConfigDataLocationResolver<SecretsResource> {
public boolean isResolvable(ConfigDataLocationResolverContext ctx, ConfigDataLocation loc) {
return loc.hasPrefix("secrets://");
}
public List<SecretsResource> resolve(ConfigDataLocationResolverContext ctx, ConfigDataLocation loc) {
return List.of(new SecretsResource(loc.getNonPrefixedValue("secrets://"))); // "payments"
}
}
class SecretsDataLoader implements ConfigDataLoader<SecretsResource> {
public ConfigData load(ConfigDataLoaderContext ctx, SecretsResource res) throws IOException {
Map<String, Object> values = client(ctx).fetch(res.name());
return new ConfigData(List.of(new MapPropertySource("secrets:" + res.name(), values)));
}
}

The advantage is that the import is visible in configuration, sits in the normal config data order, can be profile-specific with spring.config.activate.on-profile, and gets optional handling for free. The EnvironmentPostProcessor is simpler to write and gives full control over where the source goes; for a company-wide secrets integration, ConfigData is usually the cleaner contract.

5Handling Failure and Keeping Secrets Secret

The secrets service will sometimes be down, and the code must decide what that means. For a service that cannot work without its database password, failing fast is right: throw an exception with a clear message, the instance does not start, and the orchestrator keeps the old instances running. For an optional integration, the optional: prefix in ConfigData, or a guarded fetch in the post processor, lets the application start without the values. What we must not do is catch the error silently and continue with missing secrets, because the failure then appears later as a confusing authentication error.

Secrets must never reach the logs. That means logging counts and names of sources, never values, not printing the PropertySource in toString-style debug output, and keeping the actuator env endpoint masked. Spring Boot sanitizes keys that look sensitive, such as those containing password or secret, but our own source may hold keys with other names, so an explicit SanitizingFunction bean or a naming convention that matches the sanitizer is a good safety net.

6Follow-up questions

Why not just fetch the secrets in a @Configuration class or a bean?

Because by then the Environment has already been used to evaluate conditions and may have been read by other beans. A datasource auto-configuration, for example, may be created before our bean runs. Adding values to the Environment before the context exists guarantees that every bean and condition sees them.

How do I test an EnvironmentPostProcessor?

For a unit test, create a StandardEnvironment, call postProcessEnvironment with a stubbed client, and assert on environment.getProperty. For the registration, a small @SpringBootTest that asserts a known secret is present catches a wrong spring.factories key.

Should secrets have the highest priority?

It depends on the team's rules. Highest priority prevents accidental overrides, which some security teams want. Placing them below command-line arguments keeps local debugging easy. Whatever we choose, we document it, because developers will otherwise be surprised when a value they set has no effect.

7Conclusion

In this answer, we added values from an internal secrets service before the application context is created. An EnvironmentPostProcessor, ordered after config data loading and registered in META-INF/spring.factories, fetches the values and adds a PropertySource with addFirst or addAfter; its package changed in Spring Boot 4, so the key must match the version. The ConfigData API with a resolver, a loader and spring.config.import is the more declarative alternative with optional imports built in. We chose fail fast or optional loading deliberately and kept secret values out of every log.

What to say in the interviewAbout 80 seconds aloud

Open with

Because the values must exist before any bean or condition reads them, I would hook into environment preparation. The simplest way is an EnvironmentPostProcessor. I order it just after the ConfigDataEnvironmentPostProcessor so application.yml is already loaded and I can read the secrets service URL.

Then, if they want more

It fetches the values and adds a MapPropertySource with getPropertySources, either addFirst, so nothing can override a secret, or addAfter the command-line source, so command-line arguments still win. I register it in META-INF/spring.factories under the EnvironmentPostProcessor interface name, and I would check the Spring Boot version, because the interface moved package in Boot 4 and a wrong key fails silently.

Logging is not set up yet, so I use the DeferredLogFactory constructor parameter. The more modern option is the ConfigData API: a ConfigDataLocationResolver for a prefix like secrets:// and a ConfigDataLoader that returns the property sources, used with spring.config.import. That makes the import visible in configuration and supports the optional prefix.

For failure handling, a service that needs its credentials should fail fast with a clear message; an optional integration uses an optional import. And I never log values, only counts or source names, and keep the env endpoint masked.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 4, Spring Boot 2.4, Spring Boot 3
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How would you add a custom PropertySource, for example values read from an internal...": https://scrivio-interview-library.netlify.app/spring-boot/spring-configuration/0c9f7f40bb/