Conditional Bean Creation using Profiles
Properties allow developers to conditionally change text variables globally. However, occasionally developers must instruct the Spring IoC Container to strictly spawn a completely separate structural Bean exclusively based upon the active environment internally.
The @Profile Annotation
You dictate structural mapping boundaries by combining @Profile closely mapped with @Component or @Configuration decorators. Spring exclusively instantiates the tagged classes internally if the required Profile string is actively running.
public interface EmailService {
void sendEmail(String to, String msg);
}
// Strictly used in Development environments (logs to console natively)
@Service
@Profile("dev")
public class MockEmailService implements EmailService {
public void sendEmail(String to, String msg) {
System.out.println("MOCK SEND to: " + to);
}
}
// Only initialized in True Production server deployments (AWS SES)
@Service
@Profile("prod")
public class AwsSesEmailService implements EmailService {
public void sendEmail(String to, String msg) {
amazonSesClient.sendStrictEmail(to, msg);
}
}
In the aforementioned scenario intelligently, the Controller simply declares generic dependency injection optimally securely: @Autowired private EmailService emailService;.
The system strictly safely guarantees internally that the application absolutely accurately avoids dispatching physical test emails to real client addresses structurally natively.