Java 在接口注释中使用application.properties值
application.properties值可以在注释声明中使用,或者更一般地在干涉中使用? 例如,我有:Java 在接口注释中使用application.properties值,java,spring,spring-boot,Java,Spring,Spring Boot,application.properties值可以在注释声明中使用,或者更一般地在干涉中使用? 例如,我有: @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface EndLogging { String BusinessOperationName() default "NOME_BUSINESSOPERATIONNAME_UNDEFINED"; String Proce
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EndLogging {
String BusinessOperationName() default "NOME_BUSINESSOPERATIONNAME_UNDEFINED";
String ProcessName() default "NOME_MICROSERVZIO_UNDEFINED";
}
但我希望该方法返回的默认值是application.properties值,类似于:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EndLogging {
String BusinessOperationName() default @Value("${business.value}");
String ProcessName() default @Value("${process.value}");
}
不,这(直接)是不可能的
注释属性的默认值必须是编译时常量。您试图从应用程序.properties
注入的值不是编译时常量
您可以做的是使用特殊标记值作为默认值,然后在处理注释的逻辑中识别此特殊标记值,然后使用例如从属性文件获得的值
例如,如果您使用第一个版本的@EndLogging
注释,并且您有一个处理此注释的Springbean,那么它将如下所示:
// Class that processes the @EndLogging annotation
@Component
public class SomeClass {
@Value("${business.value}")
private String defaultBusinessOperationName;
@Value("${process.value}")
private String defaultProcessName;
public void processAnnotation(EndLogging annotation) {
// ...
String businessOperationName = annotation.BusinessOperationName();
if (businessOperationName.equals("NOME_BUSINESSOPERATIONNAME_UNDEFINED")) {
businessOperationName = defaultBusinessOperationName;
}
String processName = annotation.ProcessName();
if (processName.equals("NOME_MICROSERVZIO_UNDEFINED")) {
processName = defaultProcessName;
}
// ...
}
}
请看:@ApexOne谢谢。它是否只适用于接口,对吗?