Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

Show two ways to register beans programmatically in Spring, for example registering one client bean per entry in a configuration list.

The simplest way is GenericApplicationContext.registerBean(name, Type.class, supplier), called before refresh, for example from an ApplicationContextInitializer. The more container-friendly way is a BeanDefinitionRegistryPostProcessor that reads the configured list from the Environment and registers one definition per entry in postProcessBeanDefinitionRegistry. An ImportBeanDefinitionRegistrar brought in with @Import, and in Spring Framework 7 the new BeanRegistrar API, are further options. In every case we read properties through the Environment, because @ConfigurationProperties beans do not exist yet at registration time.

Why this question is asked

Most beans are declared statically with @Component or @Bean. But sometimes the number of beans depends on configuration: one HTTP client per downstream service, one DataSource per tenant, one Kafka listener per topic. Writing a @Bean method per entry does not work when the list changes per environment. Interviewers ask this coding question to see whether we know the container's registration hooks and, more importantly, what is and is not available when they run. In this answer, we will set up the example configuration, register clients first with registerBean and a supplier, then with a BeanDefinitionRegistryPostProcessor, look briefly at ImportBeanDefinitionRegistrar and the Spring Framework 7 BeanRegistrar, and explain the timing rule that trips most people up.

1The Example: One Client per Configured Service

Assume the application lists its downstream services in application.yml. We want a bean named inventoryClient and a bean named pricingClient, each a RestClient with its own base URL and timeout, so that other beans can inject them by name with @Qualifier.

YAML
# application.yml
acme:
clients:
inventory:
base-url: https://inventory.internal
timeout: 2s
pricing:
base-url: https://pricing.internal
timeout: 500ms
// A plain holder for one entry
public record ClientProps(URI baseUrl, Duration timeout) {}

The challenge is that the bean names come from the keys of the map, which are only known when the configuration is read.

2Way 1: registerBean With a Supplier

GenericApplicationContext, the base of the contexts Spring Boot uses, has registerBean(name, Type.class, supplier, customizers...). The supplier is a lambda the container calls when it creates the bean, so no reflection is needed. We must call it before the context is refreshed. In Spring Boot, an ApplicationContextInitializer runs at exactly that moment, and the Environment is already prepared by then.

Java
public class ClientInitializer implements ApplicationContextInitializer<GenericApplicationContext> {
@Override
public void initialize(GenericApplicationContext ctx) {
Map<String, ClientProps> clients = Binder.get(ctx.getEnvironment())
.bind("acme.clients", Bindable.mapOf(String.class, ClientProps.class))
.orElse(Map.of()); // {inventory=..., pricing=...}
clients.forEach((name, props) ->
ctx.registerBean(name + "Client", RestClient.class,
() -> RestClient.builder().baseUrl(props.baseUrl().toString()).build(),
bd -> bd.setLazyInit(false))); // inventoryClient, pricingClient
}
}
// Register the initializer
new SpringApplicationBuilder(App.class).initializers(new ClientInitializer()).run(args);

Notice the Binder. It is Spring Boot's binding engine, the same one that fills @ConfigurationProperties, used directly on the Environment. It converts the 2s and 500ms strings into Duration and the URLs into URI, with relaxed names such as base-url to baseUrl. This approach is short and fast, but the initializer must be registered on the SpringApplication, either in code or in META-INF/spring.factories, which makes it less discoverable than a bean.

3Way 2: A BeanDefinitionRegistryPostProcessor

A BeanDefinitionRegistryPostProcessor is a special BeanFactoryPostProcessor that runs very early in refresh and receives the BeanDefinitionRegistry, so it can add definitions. Because it is itself a bean, it can live in normal configuration. We declare its @Bean method static, so Spring can create it without first creating the configuration class, and we pass the Environment into the method.

Java
@Configuration(proxyBeanMethods = false)
class ClientsConfig {
@Bean
static BeanDefinitionRegistryPostProcessor clientRegistrar(Environment env) {
return registry -> {
Map<String, ClientProps> clients = Binder.get(env)
.bind("acme.clients", Bindable.mapOf(String.class, ClientProps.class))
.orElse(Map.of());
clients.forEach((name, props) -> {
var bd = new RootBeanDefinition(RestClient.class,
() -> RestClient.builder().baseUrl(props.baseUrl().toString()).build());
bd.addQualifier(new AutowireCandidateQualifier(Qualifier.class, name)); // @Qualifier("inventory")
registry.registerBeanDefinition(name + "Client", bd);
});
};
}
}
// Elsewhere
OrderService(@Qualifier("inventoryClient") RestClient inventory) { ... } // injected by bean name
Step throughWhen each registration hook runs
SpringApplicationApplicationContextRegistry post-processorBean factory
prepare Environment, bind nothing yet
run ApplicationContextInitializers: registerBean() works here
refresh()
postProcessBeanDefinitionRegistry(registry)
register inventoryClient, pricingClient definitions
create singletons, including @ConfigurationProperties beans

6 messages in order. Play them, or step through them one at a time.

Both hooks run before any @ConfigurationProperties bean exists, so they read the Environment.

Since Spring Framework 6.1, postProcessBeanFactory has a default empty implementation, so the interface can be written as a lambda as above; on older versions, implement both methods. Notice that the definition carries an instance supplier, which keeps creation fast and explicit. Adding a qualifier lets callers use the short name too.

4Way 3: ImportBeanDefinitionRegistrar and the New BeanRegistrar

An ImportBeanDefinitionRegistrar is brought in through @Import, usually on an @Enable annotation of a library. Its registerBeanDefinitions method receives the annotation metadata of the importing class, so the annotation's attributes can drive registration, for example @EnableAcmeClients(prefix = "acme.clients"). It can implement EnvironmentAware to read properties the same way.

Spring Framework 7 adds a dedicated BeanRegistrar interface for programmatic registration, used with @Import on a configuration class. Its register method receives a BeanRegistry and the Environment, and offers a fluent way to register beans with a supplier, which also fits Spring AOT. The exact method names may differ between milestones and releases, so check your version before relying on the snippet.

Java
class ClientsRegistrar implements BeanRegistrar {
@Override
public void register(BeanRegistry registry, Environment env) {
Binder.get(env).bind("acme.clients", Bindable.mapOf(String.class, ClientProps.class))
.orElse(Map.of())
.forEach((name, props) -> registry.registerBean(name + "Client", RestClient.class,
spec -> spec.supplier(ctx -> RestClient.builder()
.baseUrl(props.baseUrl().toString()).build())));
}
}
@Configuration
@Import(ClientsRegistrar.class)
class AppConfig {}

5The Timing Trap: No @ConfigurationProperties Yet

The most common mistake is trying to inject a @ConfigurationProperties bean into the registrar.

Java
@Bean
static BeanDefinitionRegistryPostProcessor broken(AcmeClientsProperties props) { // BROKEN
return registry -> props.getClients().forEach(...);
}
// Either fails, or creates AcmeClientsProperties too early, unbound or half processed,
// and Spring logs that it is not eligible for getting processed by all BeanPostProcessors

The reason is the order of refresh. Registration hooks run while Spring is still collecting recipes. @ConfigurationProperties classes are ordinary beans, bound by a BeanPostProcessor when they are created, and that only happens later. So at registration time the only reliable source is the Environment, read directly or through Binder. That is why every working example above calls Binder.get(env) instead of injecting a properties bean.

6Follow-up questions

Which approach would you choose for a library?

For a library, an auto-configuration that contains a static BeanDefinitionRegistryPostProcessor bean, or an @Enable annotation with an ImportBeanDefinitionRegistrar, because users get it just by adding the dependency or the annotation. An ApplicationContextInitializer requires registration on the SpringApplication, which is less discoverable. On Spring Framework 7, a BeanRegistrar is the most direct option.

Why use an instance supplier instead of setting a bean class?

A supplier tells the container exactly how to create the object, so Spring does not need to pick a constructor by reflection or resolve arguments. It is faster, it works with classes like RestClient that are built through a builder, and it is clearer to read. The trade-off is that Spring cannot inject dependencies into the supplier's object for us unless we look them up ourselves.

Do dynamically registered beans work with Spring AOT?

With care. The AOT step runs registration at build time, so the list of clients is fixed by the configuration present during the build. If the list changes per environment, the generated code will not match. Check your version's AOT documentation, and consider the single-registry-bean alternative when the set of clients is truly dynamic.

7Conclusion

In this answer, we registered one client bean per configured entry in two main ways: GenericApplicationContext.registerBean with a supplier from an ApplicationContextInitializer, and a static BeanDefinitionRegistryPostProcessor that builds definitions in postProcessBeanDefinitionRegistry. We also saw ImportBeanDefinitionRegistrar for @Enable-style libraries and Spring Framework 7's BeanRegistrar. In all of them we read the configuration through the Environment with Binder, because @ConfigurationProperties beans do not exist yet when definitions are registered.

What to say in the interviewAbout 80 seconds aloud

Open with

I would show two ways. The first is registerBean on a GenericApplicationContext, which takes a name, a type and a supplier. It has to happen before refresh, so in Spring Boot I would do it in an ApplicationContextInitializer: bind acme.clients from the Environment as a Map of name to properties using Boot's Binder, then for each entry call registerBean with a name like inventoryClient and a supplier that builds a RestClient with that base URL.

Then, if they want more

The second, which I prefer for shared code, is a BeanDefinitionRegistryPostProcessor declared as a static @Bean method that takes the Environment. In postProcessBeanDefinitionRegistry it binds the same map and registers a RootBeanDefinition with an instance supplier for each client, optionally adding a qualifier so callers can inject with @Qualifier.

For libraries there is also ImportBeanDefinitionRegistrar through an @Enable annotation, and Spring Framework 7 adds a BeanRegistrar interface for exactly this, though I would check the API in the version we use.

The one rule I always mention is timing: these hooks run while Spring is still collecting definitions, before any ordinary beans exist, so I cannot inject a @ConfigurationProperties bean there. It either fails or gets created too early without its post-processing. Reading the Environment through Binder is the correct way.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 7, Spring Framework 6
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 "Show two ways to register beans programmatically in Spring, for example registering one...": https://scrivio-interview-library.netlify.app/spring-boot/ioc-container/f3a27ac2b3/