Martin Mucha
Martin Mucha

Reputation: 3091

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.

Upvotes: 2

Views: 1053

Answers (2)

Martin Mucha
Martin Mucha

Reputation: 3091

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.

Upvotes: 1

crizzis
crizzis

Reputation: 10716

I'm sure there are a couple of ways, but the easiest is probably:

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

Upvotes: 0

Related Questions