Spring Expression Language (SpEL) with @Value: dollar vs. hash ($ vs. #)

SpringDependency InjectionSpring El

Spring Problem Overview


I'm a little confused concerning when to use ${...} compared to #{...}. Spring's documentation only uses #{...}, but there are plenty of examples that use ${...}. Furthermore, when I started with SpEL I was told to use ${...} and it works fine.

For those who are confused, an example of how I use it would be

@Component
public class ProxyConfiguration {

	@Value("${proxy.host}")
	private String host;
	@Value("${proxy.port}")
	private String port;

	:
}

and some property file:

proxy.host=myproxy.host
proxy.port=8000

My questions are:

  • what are the differences or is it the same?
  • is one version deprecated so I should use the other one?

Spring Solutions


Solution 1 - Spring

${...} is the property placeholder syntax. It can only be used to dereference properties.

#{...} is SpEL syntax, which is far more capable and complex. It can also handle property placeholders, and a lot more besides.

Both are valid, and neither is deprecated.

Solution 2 - Spring

${expr} --> Immediate Evaluation

#{expr} --> Deferred Evaluation

> Immediate evaluation means that the expression is evaluated and the result returned as soon as the page is first rendered. Deferred evaluation means that the technology using the expression language can use its own machinery to evaluate the expression sometime later during the page’s lifecycle, whenever it is appropriate to do so.

Complete reference here

There is no JSP EL, JSP uses SpEL. SpEL fits to technology that is using it.

Solution 3 - Spring

Try reading this article, which suggests

"If the hash is used, your code is recomputed every time that element is included in a partial refresh (i.e. each time it is rendered). If you use a dollar, your code is only computed when the page is initially loaded. But this has been extended beyond just EL, to SSJS too. After the hash or dollar, the curly braces denote the start and end of your language. This will be important when we come to combining languages later."

Solution 4 - Spring

Expression Language Specification • Final Release - May 8, 2006

Page 2:

An eval-expression is formed by using the constructs ${expr} or #{expr}. Both constructs are parsed and evaluated in exactly the same way by the EL, even though they might carry different meanings in the technology that is using the EL.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsjngmView Question on Stackoverflow
Solution 1 - SpringskaffmanView Answer on Stackoverflow
Solution 2 - SpringXvrCJView Answer on Stackoverflow
Solution 3 - Springchrisp7575View Answer on Stackoverflow
Solution 4 - SpringMellonView Answer on Stackoverflow