ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-10-26 01:01:01  阅读:149  来源: 互联网

标签:dependency-injection spring java


因此,我有一个可以在多个不同国家/地区启动的应用程序,例如:
mvn clean package -Dcountry = FRANCE
分别
mvn clean package -Dcountry =德国

对于不同的国家/地区,我会有不同的行为,尤其是在验证内容时.

所以我有一个包含依赖国家/地区验证器的类:

@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);
    }
}

第一个依赖国家的验证者:

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

第二个依赖国家的验证者:
让我们假设

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

我的问题是

>当应用程序以“ -Dcountry = FRANCE”启动时,如何管理将MyCountrySpecificValidator1的实例注入SomeValidatingClass中

和.

>当应用程序以“ -Dcountry = GERMANY”启动时,如何管理将MyCountrySpecificValidator2实例注入SomeValidatingClass中

解决方法:

您可以使用@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();
  }

在哪里

public class LinuxCondition implements Condition{

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

您可以使用所需的任何属性

要么

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

阅读here

更新:

更简单

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

标签:dependency-injection,spring,java
来源: https://codeday.me/bug/20191026/1932844.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有