Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring expression languague - determine if servletContext variable is defined

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?

like image 345
user1531567 Avatar asked Mar 18 '23 11:03

user1531567


1 Answers

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.

like image 191
Gary Russell Avatar answered Apr 27 '23 11:04

Gary Russell