To switch between SMS and email message delivery in a Spring Boot application at runtime, you must avoid relying on
Context.refresh() with
@Profile beans because it often fails to reinitialize conditional components. Instead, implement a strategy pattern using a primary service interface and inject the specific implementation via configuration properties or a dynamic registry. This approach ensures that the correct messaging channel is selected without restarting the application context or risking bean initialization errors.
The Problem with Context Refresh and Profiles
Many developers attempt to change active profiles dynamically by calling
ConfigurableApplicationContext.refresh() after updating the
spring.profiles.active property. While this works for simple property changes, it is dangerous for beans annotated with
@Profile. When the context refreshes, Spring does not automatically destroy and recreate profile-specific beans in a way that guarantees consistency. This can lead to stale references, null pointers, or beans remaining in an undefined state. The error occurs because the lifecycle management of profiled beans is tightly coupled to the initial context startup phase.
Implementing the Strategy Pattern
The most robust solution is to decouple the selection logic from the Spring context lifecycle. Create a common interface that defines the contract for sending messages. Both SMS and Email services should implement this interface. By injecting the interface into your business logic rather than a concrete class, you allow the application to determine which implementation to use at runtime through a separate selector mechanism.
Define the interface as follows:
public interface MessageService {
void sendMessage(String recipient, String content);
}
Create two implementations. The first handles SMS delivery:
@Component("smsService")
public class SmsMessageService implements MessageService {
@Override
public void sendMessage(String recipient, String content) {
// Logic for sending SMS via Twilio or similar provider
System.out.println("Sending SMS to " + recipient);
}
}
The second handles email delivery:
@Component("emailService")
public class EmailMessageService implements MessageService {
@Override
public void sendMessage(String recipient, String content) {
// Logic for sending email via JavaMailSender
System.out.println("Sending Email to " + recipient);
}
}
Dynamic Selection Mechanism
Instead of using
@Profile to select the bean, create a factory or a manager component that holds a map of all available services. This manager can be configured to pick the active service based on a runtime flag or a database setting. This method is safe because it does not manipulate the Spring context lifecycle.
@Component
public class MessageDispatcher {
private final Map services;
public MessageDispatcher(List services) {
this.services = services.stream()
.collect(Collectors.toMap(
service -> service.getClass().getSimpleName(),
service -> service
));
}
public void dispatch(String type, String recipient, String content) {
MessageService service = services.get(type + "MessageService");
if (service == null) {
throw new IllegalArgumentException("Unknown message type: " + type);
}
service.sendMessage(recipient, content);
}
}
This dispatcher accepts a string identifier for the message type. It looks up the corresponding bean from the injected list. Since all services are registered as beans, they are initialized once at startup. The dispatcher simply routes the call to the correct one based on the input parameter. This eliminates the need for any context manipulation.
Configuration via Properties
You can control the active message type using a standard
application.properties file. Define a property named
app.message.type. In your controller or service layer, read this property and pass it to the dispatcher. If you need to change the type during execution, update the property value and reload it, or store the preference in a database. This separation of concerns keeps your business logic clean and your configuration manageable.
For example, in your controller:
@RestController
@RequestMapping("/messages")
public class MessageController {
private final MessageDispatcher dispatcher;
public MessageController(MessageDispatcher dispatcher) {
this.dispatcher = dispatcher;
}
@PostMapping("/send")
public String send(@RequestParam String recipient,
@RequestParam String content) {
String type = "email"; // Default or fetched from config
dispatcher.dispatch(type, recipient, content);
return "Message sent successfully";
}
}
If you require real-time switching without restarting, consider adding an endpoint that updates the internal state of the
MessageDispatcher or the underlying configuration source. This provides full runtime flexibility while maintaining the stability of the Spring container. For more information on handling email configurations, see
How can an email addressed to somebody else arrive in my inbox?.
Alternative Approaches
Some teams prefer using Spring Cloud Function or reactive streams for complex routing scenarios. However, for simple SMS vs. Email switching, the strategy pattern with a dispatcher is sufficient and easier to debug. Avoid over-engineering with microservices if a single application can handle the load. The key is to prevent direct dependency injection of profile-specific beans when dynamic switching is required.
Frequently Asked Questions
Can I use @Profile with @RefreshScope?
Yes, you can annotate beans with both
@Profile and
@RefreshScope, but you must use Spring Cloud Config Server to trigger the refresh. Simply changing the property locally will not work because
@RefreshScope relies on the event listener from Spring Cloud. This adds significant complexity compared to the strategy pattern.
What happens if I remove a bean from the context manually?
Manually removing beans from the context is unsupported and likely to cause severe instability. The Spring container maintains strict ownership of bean lifecycles. Attempting to deregister a bean programmatically can leave other dependent beans in a broken state, leading to unpredictable runtime exceptions.
Is it safe to restart the ApplicationContext?
Restarting the context using
refresh() is generally unsafe for production applications. It destroys all existing beans and recreates them, which can lead to race conditions, lost session data, and incomplete initialization of external connections like database pools or message queues.
How do I handle multiple message types beyond SMS and Email?
The strategy pattern scales easily. You simply add new implementations of the
MessageService interface and register them as components. The dispatcher's map will automatically include them if you inject all implementations via
List<MessageService>. No code changes are needed in the dispatcher logic itself.
Why did my previous solution fail with Context.refresh?
Context.refresh() does not guarantee that profile-specific beans are correctly swapped out. It resets the environment but may retain references to old bean instances or fail to initialize new ones due to circular dependencies or missing metadata during the rapid lifecycle transition.