Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programatically evaluate expression(spel/variable reference) used in annotation?

Say that I have use case for finding method annotated via say @Scheduled(cron = "${variable}"), and I'd like to know the value of "cron" parameter. If I check via reflection, no surprise, I will find there value "${variable}".

Can someone share link/snipet how to evaluate variables/spel expression present in annotation? I found some answers, but neither of them worked.

like image 742
Martin Mucha Avatar asked Mar 20 '26 11:03

Martin Mucha


1 Answers

Just to extend @crizzis answer, maybe filling the missing part.

Fist you need to inject/autowire ConfigurableBeanFactory beanFactory;. Looking at implementation of ExpressionValueMethodArgumentResolver and it's parent AbstractNamedValueMethodArgumentResolver it seems to me, that full code which does variable substitution and spell needs one more line:

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

then string like #{!${some-boolean-variable} ? 'a' : 'b'} was correctly evaluated for me. Not sure if this is the way-to-go as I don't know spring well, but this worked for me.

like image 92
Martin Mucha Avatar answered Mar 22 '26 06:03

Martin Mucha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!