作者:小伟3NrJ | 来源:互联网 | 2023-08-13 13:26
因此,我有一个可以在多个不同国家地区启动的应用程序,例如: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.