Spring languague expression - determine if servletContext variable is defined

In the spring xml file, I use the spring EL expression to load the properties file differently depending 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 the web application everything is fine. However, when I run the standalone application (this means the predefined variable servletContext 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 a servletContext exists? Or somehow avoid the exception if it is not defined?

+3


source to share


1 answer


You need to evaluate presence or not, bean; you can't just check if it is null as it is trying to use a bean that doesn't exist.

The subject #root

for evaluation is BeanExpressionContext

.

This should lead 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 refer to the bean in the value part of the ternary expression (when the boolean part is true), you simply cannot refer to it in the boolean part.

+6


source







All Articles