Introducing different beans depending on environment property
So I have an application that can be run for several different countries, for example: mvn clean package -Dcountry = FRANCE respectively mvn clean package -Dcountry = GERMANY
I have different behavior in different countries, especially when I check the material.
So, I have this class which contains a country specific validator:
@Component
public class SomeValidatingClass {
private final Validator myCountrySpecificValidator;
@Autowired
public SomeValidatingClass(MyCountrySpecificValidator myCountrySpecificValidator) {
this.myCountrySpecificValidator = myCountrySpecificValidator;
}
public void doValidate(Object target, Errors errors) {
myCountrySpecificValidator.validate(target, errors);
}
}
First country-specific validator:
public class MyCountrySpecificValidator1 implements Validator {
@Override
public void validate(Object target, Errors errors) {
if (target == null) {
errors.rejectValue("field", "some error code");
}
}
}
Second country-specific validator: Let for
public class MyCountrySpecificValidator2 implements Validator {
@Override
public void validate(Object target, Errors errors) {
if (target != null) {
errors.rejectValue("field", "some other error code");
}
}
}
My question
- how can I add an instance of MyCountrySpecificValidator1 to SomeValidatingClass when the app was started with "- Dcountry = FRANCE"
and correspondingly
- how can I insert an instance of MyCountrySpecificValidator2 into SomeValidatingClass when the application was started with "- Dcountry = GERMANY"
source to share
You can use annotation @Conditional
to enforce implementation depending on conditions. Like this
@Bean(name="emailerService")
@Conditional(WindowsCondition.class)
public EmailService windowsEmailerService(){
return new WindowsEmailService();
}
@Bean(name="emailerService")
@Conditional(LinuxCondition.class)
public EmailService linuxEmailerService(){
return new LinuxEmailService();
}
where, for example,
public class LinuxCondition implements Condition{
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("os.name").contains("Linux"); }
}
and you can use any property you need
or
use an @Profile
annotation defining the active profile if you need multiple beans
read here
UPDATE:
Even easier
@ConditionalOnProperty(name = "country", havingValue = "GERMANY", matchIfMissing = true) and annotate a method which return the germany validator. And the same for France.
source to share