visit
@Autowired
@Qualifier("Email")
private MessageValidator emailValidator;
@Autowired
@Qualifier("SMS")
private MessageValidator smsValidator;
@Autowired
@Qualifier("Telegram")
private MessageValidator telegramValidator;
@Override
public void processMessage(Message msg) {
boolean isValid = false;
if (msg instanceof SMSMessage) {
isValid = smsValidator.validate(msg);
} else if (msg instanceof EmailMessage) {
isValid = emailValidator.validate(msg);
} else if (msg instanceof TelegramMessage) {
isValid = telegramValidator.validate(msg);
}
//do other processing
}
@Autowired
private MessageValidatorFactory msgValidatorFactory;
@Override
public void processMessage(Message msg) {
boolean isValid = msgValidatorFactory.getMsgValidator(msg.getType()).validate(msg);
//do other processing
}
public interface MessageValidatorFactory {
MessageValidator getMsgValidator(String msgType);
}
@Configuration
public class BeanConfigs {
@Bean("validatorFactory")
public FactoryBean serviceLocatorFactoryBean() {
ServiceLocatorFactoryBean factoryBean = new ServiceLocatorFactoryBean();
factoryBean.setServiceLocatorInterface(MessageValidatorFactory.class);
return factoryBean;
}
}
The configuration merely help to lookup the bean by beanId such as
Email
, SMS
, Telegram
@Component("Email")
public class EmailMessageValidator implements MessageValidator {
@Override
public boolean validate(Message m) {
//logic for validation
return false;
}
}
@Component("SMS")
public class SMSMessageValidator implements MessageValidator {
@Override
public boolean validate(Message m) {
//logic for validation
return false;
}
}
@Component("Telegram")
public class TelegramMessageValidator implements MessageValidator {
@Override
public boolean validate(Message m) {
//logic for validation
return false;
}
}