How to Dynamically Autowire Beans in Spring: Two Practical Approaches
This tutorial explains why and how to dynamically change Spring bean implementations at runtime, presenting a real-world region‑service example and demonstrating two solutions—using BeanFactory and injecting a map of implementations—for flexible backend development.
1. Introduction
In this short tutorial we show how to dynamically autowire a Bean in Spring.
We first present a realistic use case where dynamic autowiring is useful, then demonstrate two different ways to solve the problem.
2. Use Cases for Dynamic Autowiring
Dynamic autowiring is handy wherever the execution logic of a Spring Bean needs to change at runtime, especially when a runtime variable decides which code to run.
To illustrate, we create an application that controls servers in different regions. The interface looks like:
public interface RegionService {
boolean isServerActive(int serverId);
String getISOCountryCode();
}And two implementations:
@Service("GBregionService")
public class GBRegionService implements RegionService {
@Override
public boolean isServerActive(int serverId) {
return false;
}
@Override
public String getISOCountryCode() {
return "GB";
}
} @Service("USregionService")
public class USRegionService implements RegionService {
@Override
public boolean isServerActive(int serverId) {
return true;
}
@Override
public String getISOCountryCode() {
return "US";
}
}Assume a website lets users check whether a server in a specific region is active. We want to switch the RegionService implementation based on user input – a perfect scenario for dynamic bean autowiring.
3. Using BeanFactory
BeanFactory is the root interface for accessing the Spring Bean container. Because BeanFactory itself is a Spring Bean, we can autowire it and retrieve beans by name:
@Service
public class BeanFactoryDynamicAutowireService {
private static final String SERVICE_NAME_SUFFIX = "regionService";
private final BeanFactory beanFactory;
@Autowired
public BeanFactoryDynamicAutowireService(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
public boolean isServerActive(String isoCountryCode, int serverId) {
RegionService service = beanFactory.getBean(getRegionServiceBeanName(isoCountryCode), RegionService.class);
return service.isServerActive(serverId);
}
private String getRegionServiceBeanName(String isoCountryCode) {
return isoCountryCode + SERVICE_NAME_SUFFIX;
}
}We use the overloaded getBean() method to obtain the bean with the given name and type. While this works, a more idiomatic approach is preferred.
4. Using a Map of Implementations
Spring can collect all implementations of an interface into a Map where the key is the bean name. This allows us to inject the map and look up the appropriate implementation:
@Service
public class CustomMapFromListDynamicAutowireService {
private final Map<String, RegionService> servicesByCountryCode;
@Autowired
public CustomMapFromListDynamicAutowireService(List<RegionService> regionServices) {
servicesByCountryCode = regionServices.stream()
.collect(Collectors.toMap(RegionService::getISOCountryCode, Function.identity()));
}
public boolean isServerActive(String isoCountryCode, int serverId) {
RegionService service = servicesByCountryCode.get(isoCountryCode);
return service.isServerActive(serverId);
}
}We build a map of implementations keyed by ISO country code in the constructor and use it to retrieve the correct service at runtime.
5. Summary
This quick tutorial demonstrated two ways to dynamically autowire beans in Spring: using BeanFactory directly and injecting a map of all implementations.
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.
