Mastering Spring BeanRegistrar: Fine‑Grained Programmatic Bean Registration
This article explains how to use Spring's BeanRegistrar to programmatically register beans with precise scope, lazy initialization, and custom providers, offering advantages over traditional annotation‑based configuration and demonstrating the approach with a complete GreetingService example.
The BeanRegistrar interface is useful when you want to register beans programmatically in the application context without relying on @Bean, @Configuration, or @Component. Instead, you use the abstract BeanRegistry to dynamically register beans.
1. Advantages of BeanRegistrar
Fine‑grained control : You can precisely define a bean’s scope, initialization strategy, and provider instead of depending solely on annotations.
Profile‑specific configuration : Beans can be conditionally registered based on the active configuration profile, enabling flexible runtime customization.
Lazy initialization and prototype scope : Supports advanced lifecycle management to optimize resource usage.
Support for advanced runtime scenarios : Using BeanRegistrar can improve performance and compatibility in ahead‑of‑time compiled environments.
2. Example: Simple Bean Registration with BeanRegistrar
We demonstrate a simple GreetingService example. Instead of annotating the class with @Service or defining it with @Bean, we register it dynamically via BeanRegistrar.
public class GreetingService {
private final String greeting;
public GreetingService() {
this("Hello");
}
public GreetingService(String greeting) {
this.greeting = greeting;
}
public String greet(String name) {
return greeting + ", " + name + "!";
}
}The service provides a customizable greeting message.
Registering the Bean with BeanRegistrar
We create a configuration class that imports a custom registrar.
@Configuration
@Import(GreetingServiceRegistrar.class)
public class AppConfig {
}
class GreetingServiceRegistrar implements BeanRegistrar {
@Override
public void register(BeanRegistry registry, Environment env) {
// Register the default GreetingService
registry.registerBean("greetingService", GreetingService.class);
// Register a prototype‑scoped, lazy‑initialized bean with a custom provider
registry.registerBean("customGreetingService", GreetingService.class, spec ->
spec.prototype()
.lazyInit()
.description("Custom GreetingService bean")
.supplier(context -> new GreetingService("Hi there"))
);
}
}In this configuration, the default bean named greetingService is registered first. Then a second bean customGreetingService is added, defined as prototype scoped, lazy‑initialized, and supplied by a custom factory that returns a different greeting.
Using the Registered Beans
After programmatic registration, the beans can be retrieved and used like any other Spring‑managed bean. The following CommandLineRunner fetches both beans from the application context and invokes their greet() methods.
@Component
public class GreetingRunner implements CommandLineRunner {
private final ApplicationContext context;
public GreetingRunner(ApplicationContext context) {
this.context = context;
}
@Override
public void run(String... args) {
GreetingService defaultService = context.getBean("greetingService", GreetingService.class);
GreetingService customService = context.getBean("customGreetingService", GreetingService.class);
System.out.println(defaultService.greet("Spring Developer"));
System.out.println(customService.greet("Spring Boot User"));
}
}The console output is:
Hello, Spring Developer!
Hi there, Spring Boot User!3. Conclusion
This article explored how to use Spring's BeanRegistrar to programmatically register beans with different scopes, lazy initialization, and custom providers. This approach gives developers fine‑grained control over bean registration, especially for advanced use cases where annotation‑based configuration is insufficient.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
