In a spring context xml file, I am using a spring EL expression to load a properties file differently based on whether the servletContext predefined variable is null or not. Below is the Spel expression (formatted for readability):
#{
systemProperties['my.properties.dir'] != null ?
'file:' + systemProperties['my.properties.dir'] + '/' :
(servletContext != null ?
'file:/apps/mydir' + servletContext.getContextPath() + '/' :
'classpath:')
}my.properties
When I run in a web application, everything is fine. However, when I run in a standalone application (meaning the servletContext predefined variable is not defined), I get the following error:
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 109): Field or property 'servletContext' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'
Is there a way to determine if servletContext exists? Or some way to avoid the exception when it is not defined?
You need to evaluate the presence, or not, of the bean; you can't just test if it's null because that attempts to use the bean, which doesn't exist.
The #root
object for the evaluation is a BeanExpressionContext
.
This should head you in the right direction...
<bean id="foo" class="java.lang.String">
<constructor-arg value="#{containsObject('bar') ? bar : 'foo'}" />
</bean>
<bean id="bar" class="java.lang.String">
<constructor-arg value="bar" />
</bean>
So you would use...
#{containsObject('servletContext') ? ... servletContext.contextPath ... : ...
Note that you can "reference" the bean in the value part of the ternary expression (when the boolean part evaluates to true), you just can't reference it in the boolean part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With