热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

因此,我有一个可以在多个不同国家地区启动的应用程序,例如:mvncleanpackage-DcountryFRANCE分别mvncleanpackage-Dcountry德国对于不

因此,我有一个可以在多个不同国家/地区启动的应用程序,例如:
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.


推荐阅读
author-avatar
小伟3NrJ
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有