Your code defines a producer method in the EmailServiceProvider
class that dynamically creates and provides an implementation of EmailService
based on the configuration (email.driver
). The choice of the email client to be used (e.g., SqsEmailServiceImpl
or LocalSmtpEmailServiceImpl
) is determined by the email.driver
value.
The produced EmailService
can be injected wherever it's needed within your application. Here's a breakdown of the steps:
The configuration value email.driver
must be available to the application. Depending on the environment or framework, you can set this in various ways:
-
microprofile-config.properties
file:email.driver=sqs
-
Environment Variable:
export email.driver=sqs
-
System Property:
-Demail.driver=sqs
In classes that require EmailService
, inject it using CDI (@Inject
):
package com.gappify.messaging;
import javax.inject.Inject;
public class EmailManager {
@Inject
private EmailService emailService;
public void sendEmail(String recipient, String subject, String body) {
emailService.send(recipient, subject, body);
}
}
For this to work:
- The
EmailService
interface must be implemented bySqsEmailServiceImpl
andLocalSmtpEmailServiceImpl
. - Both implementations must be valid CDI beans (annotated with
@ApplicationScoped
,@Dependent
, etc.).
Example:
package com.gappify.messaging.service;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class SqsEmailServiceImpl implements EmailService {
@Override
public void send(String recipient, String subject, String body) {
// Logic for sending email via SQS
}
}
package com.gappify.messaging.service;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class LocalSmtpEmailServiceImpl implements EmailService {
@Override
public void send(String recipient, String subject, String body) {
// Logic for sending email via Local SMTP
}
}
When the application runs:
- The
EmailServiceProvider
producer is invoked. - The producer reads the value of
email.driver
from the configuration. - The corresponding implementation (
SqsEmailServiceImpl
orLocalSmtpEmailServiceImpl
) is instantiated and injected whereverEmailService
is used.
- Ensure the
email.driver
configuration value is correctly set and accessible. - Confirm the implementations (
SqsEmailServiceImpl
,LocalSmtpEmailServiceImpl
) are correctly annotated and discoverable by CDI. - Use a logging or debugging mechanism to verify which implementation is being selected.
This structure ensures flexibility, as you can easily switch email drivers by changing the configuration without modifying the application code.