本文介绍了将外化值注入Spring注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我一直在考虑在编译时评估注释值的Java功能,它似乎真的难以外化注释值。I've been thinking around the Java feature that evaluates annotation values in compile-time and it seems to really make difficult externalizing annotation values.然而,我是不确定它是否真的不可能,所以我很感激任何建议或明确的答案。However, I am unsure whether it is actually impossible, so I'd appreciate any suggestions or definitive answers on this.更重要的是,我试图外化一个控制的注释值Spring中预定方法调用之间的延迟,例如:More to the point, I am trying to externalize an annotation value which controls delays between scheduled method calls in Spring, e.g.:public class SomeClass { private Properties props; private static final long delay = 0; @PostConstruct public void initializeBean() { Resource resource = new ClassPathResource("scheduling.properties"); props = PropertiesLoaderUtils.loadProperties(resource); delay = props.getProperties("delayValue"); } @Scheduled(fixedDelay = delay) public void someMethod(){ // perform something }}假设 scheduling.properties 在类路径上并包含属性键 delayValue 及其对应的long值。Suppose that scheduling.properties is on classpath and contains property key delayValue along with its corresponding long value.现在,这段代码有明显的编译错误,因为我们是尝试将值赋给 final 变量,但这是必需的,因为我们无法将变量赋值给注释值,除非它是 static final 。Now, this code has obvious compilation errors since we're trying to assign a value to final variable, but that is mandatory, since we can't assign the variable to annotation value, unless it is static final.有没有办法解决这个问题?我一直在考虑Spring的自定义注释,但根本问题仍然存在 - 如何将外化值分配给注释?Is there any way of getting around this? I've been thinking about Spring's custom annotations, but the root issue remains - how to assign the externalized value to annotation?欢迎任何想法。编辑:一个小更新 - 对于这个例子,Quartz集成是过度的。我们只需要以亚分钟的分辨率进行定期执行即可。 A small update - Quartz integration is overkill for this example. We just need a periodic execution with sub-minute resolution and that's all.推荐答案 @Scheduled 注释已将String参数添加到原始的3个长参数中以处理此问题。 fixedDelayString , fixedRateString 和 initialDelayString 现在也可用: @Scheduled(fixedDelayString = "${my.delay.property}") public void someMethod(){ // perform something } 这篇关于将外化值注入Spring注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-11 04:45