Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 如何以编程方式计算注释中使用的表达式(spel/变量引用)?_Spring_Spring Boot - Fatal编程技术网

Spring 如何以编程方式计算注释中使用的表达式(spel/变量引用)?

Spring 如何以编程方式计算注释中使用的表达式(spel/变量引用)?,spring,spring-boot,Spring,Spring Boot,假设我有通过Say@Scheduled(cron=“${variable}”)查找注释方法的用例,我想知道“cron”参数的值。如果我通过反射进行检查,毫不奇怪,我会发现有值“${variable}” 有人可以分享link/snipet如何计算注释中的变量/spel表达式吗?我找到了一些答案,但它们都不起作用。我肯定有几种方法,但最简单的可能是: beanFactory.getBeanExpressionResolver().evaluate( "${variable}&quo

假设我有通过Say
@Scheduled(cron=“${variable}”)
查找注释方法的用例,我想知道“cron”参数的值。如果我通过反射进行检查,毫不奇怪,我会发现有值
“${variable}”


有人可以分享link/snipet如何计算注释中的变量/spel表达式吗?我找到了一些答案,但它们都不起作用。

我肯定有几种方法,但最简单的可能是:

beanFactory.getBeanExpressionResolver().evaluate(
    "${variable}", 
    new BeanExpressionContext(beanFactory, null))

只是为了扩展@crizzis的答案,也许可以填充缺少的部分

首先,您需要注入/autowire
ConfigurableBeanFactory beanFactory。查看
ExpressionValueMethodArgumentResolver
及其父级
AbstractNamedValueMethodArgumentResolver
的实现,在我看来,完成变量替换和拼写的完整代码还需要一行:

BeanExpressionResolver beanExpressionResolver = beanFactory.getBeanExpressionResolver();    
String expressionWithSubstitutedVariables = beanFactory.resolveEmbeddedValue(expression);
Object resultWithResolvedSPEL = beanExpressionResolver.evaluate(expressionWithSubstitutedVariables, new BeanExpressionContext(beanFactory, null));

然后像
{!${some boolean variable}?'a':'b'}
这样的字符串被正确地计算出来。我不确定这是否是一条路,因为我不太了解spring,但这对我很有效。

谢谢,但出于某种原因,这对我不起作用。像
{3*3}
这样的SPEL被计算,但是像
${variable}
这样的现有变量引用没有被计算,并且只返回相同的字符串。查看代码我可以强制它查找
${/code>,而不是
#{
,但这似乎不支持对变量求值,只支持spel。有什么东西可以同时做这两件事,比如说
@Value
注释吗?或者您可以提供完整的示例,因为这一个似乎不能按预期工作。