use*_*567 4 java spring spring-el
在spring上下文xml文件中,我使用spring EL表达式根据servletContext预定义变量是否为null来加载属性文件.下面是Spel表达式(为便于阅读而格式化):
#{
systemProperties['my.properties.dir'] != null ?
'file:' + systemProperties['my.properties.dir'] + '/' :
(servletContext != null ?
'file:/apps/mydir' + servletContext.getContextPath() + '/' :
'classpath:')
}my.properties
Run Code Online (Sandbox Code Playgroud)
当我在Web应用程序中运行时,一切都很好.但是,当我在独立应用程序中运行时(意味着未定义servletContext预定义变量),我收到以下错误:
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'
Run Code Online (Sandbox Code Playgroud)
有没有办法确定servletContext是否存在?或者某些方法在未定义时避免异常?
您需要评估bean的存在与否; 你不能只测试它是否为null因为它试图使用不存在的bean.
#root评估的对象是a BeanExpressionContext.
这应该让你朝着正确的方向前进......
<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>
Run Code Online (Sandbox Code Playgroud)
所以你会用......
#{containsObject('servletContext') ? ... servletContext.contextPath ... : ...
请注意,您可以在三元表达式的值部分中"引用"bean(当布尔部分的计算结果为true时),您无法在布尔部分中引用它.
| 归档时间: |
|
| 查看次数: |
1149 次 |
| 最近记录: |