根据提供的环境属性注入不同的 bean

Iwa*_*now 4 java spring dependency-injection

所以我有一个可以为几个不同国家启动的应用程序,例如:mvn clean package -Dcountry=FRANCE resp。mvn clean package -Dcountry=GERMANY

对于不同的国家,我有不同的行为,尤其是在验证东西时。

所以我有这个包含国家相关验证器的类:

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

第一个国家相关验证器:

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

第二个国家相关验证器:让我们假设

public class MyCountrySpecificValidator2 implements Validator {
   @Override
   public void validate(Object target, Errors errors) {
       if (target != null) {
           errors.rejectValue("field", "some other error code");
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是

  • 当应用程序以“-Dcountry=FRANCE”启动时,我如何设法将MyCountrySpecificValidator1的实例注入SomeValidatingClass

  • 当应用程序以“-Dcountry=GERMANY”启动时,我如何设法将MyCountrySpecificValidator2的实例注入SomeValidatingClass

Sta*_*avL 6

您可以@Conditional根据条件使用任一注释来提供实现。像这样

  @Bean(name="emailerService")
  @Conditional(WindowsCondition.class)
  public EmailService windowsEmailerService(){
      return new WindowsEmailService();
  }

  @Bean(name="emailerService")
  @Conditional(LinuxCondition.class)
  public EmailService linuxEmailerService(){
    return new LinuxEmailService();
  }
Run Code Online (Sandbox Code Playgroud)

哪里例如

public class LinuxCondition implements Condition{

  @Override
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    return context.getEnvironment().getProperty("os.name").contains("Linux");  }
}
Run Code Online (Sandbox Code Playgroud)

你可以使用任何你需要的财产

或者

@Profile如果您需要多个 bean,请使用定义活动配置文件的注释

在这里阅读

更新:

更简单

@ConditionalOnProperty(name = "country", havingValue = "GERMANY", matchIfMissing = true) and annotate a method which return the germany validator. And the same for France.
Run Code Online (Sandbox Code Playgroud)