Injecting different beans depending on provided environment property

Viewed 2083

So I have an application that can be started for several different countries for example: mvn clean package -Dcountry=FRANCE resp. mvn clean package -Dcountry=GERMANY

For different countries I have different behavior especially when I'm validating stuff.

So I have this class that contains a country dependent 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);
    }
}

The first country dependent validator:

public class MyCountrySpecificValidator1 implements Validator {
    @Override
    public void validate(Object target, Errors errors) {
        if (target == null) {
            errors.rejectValue("field", "some error code");
        }
    }
}

The second country dependent validator: Let's assume 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 is

  • how do I manage to inject an instance of MyCountrySpecificValidator1 into SomeValidatingClass when the application was startet with "-Dcountry=FRANCE"

and resp.

  • how do I manage to inject an instance of MyCountrySpecificValidator2 into SomeValidatingClass when the application was startet with "-Dcountry=GERMANY"
1 Answers
Related