自定义 Spring (Boot) 注解:@ConditionalOnProperty 带有默认键名

use*_*001 5 java spring spring-boot

如何创建@Country“继承”@ConditionalOnProperty但预定义属性键的自定义 Spring (Boot) 注释?

给定一些共享公共接口的服务

interface WizardService {
   void doMagic()
}
Run Code Online (Sandbox Code Playgroud)

以及通过 选择的一组特定于国家/地区的实现@ConditionalOnProperty(name = "country", havingValue = "[iso-code]"),即根据country属性的值选择实现

@ConditionalOnProperty(name = "country", havingValue = "de")
@Service
class WizardServiceGermany {
   @Override void doMagic() { System.out.println("Simsalabim!"); }
}

@ConditionalOnProperty(name = "country", havingValue = "en")
@Service
class WizardServiceGreatBritain {
   @Override void doMagic() { System.out.println("Wingardium Leviosa!"); }
}
Run Code Online (Sandbox Code Playgroud)

是否可以定义一个自定义 spring 注释,该注释name默认情况下始终将属性设置为“国家/地区”,以便我可以进行@Country注释?例如:

@Country("en")
@Service
class WizardServiceGreatBritain {
   @Override void doMagic() { System.out.println("Wingardium Leviosa!"); }
}
Run Code Online (Sandbox Code Playgroud)

我尝试创建一个元注释,但它被忽略了(用@ConditionalOnProperty等效的替换它工作正常):

@ConditionalOnProperty(name = "country")
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface Country {

    @AliasFor(annotation = ConditionalOnProperty.class, attribute = "havingValue")
    String havingValue() default "";
}
Run Code Online (Sandbox Code Playgroud)