最近忙公司系统的Java版本升级,blog写的不如以前勤快了。今天说说Spring配置文件中的变量。
相信用过spring的都知道Placeholder是怎么回事,是用来读取bean中的Property的。比如:
<!-- 定义property placeholder -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<!-- 通过$获取property的值 -->
<property name="driverClassName" value="${project.jdbc.driverClassName}" />
<property name="url" value="${project.jdbc.url}" />
<property name="username" value="${project.jdbc.username}" />
<property name="password" value="${project.jdbc.password}" />
而spring3引入的SPEL,使用起来更加强大,可以进行更为复杂的计算。我们常用的使用方式是通过jndi url resource来读取文件夹中的配置文件(Properties或者log4j文件)。比如:
<jee:jndi-lookup id="configUrlResource"
jndi-name="java:comp/env/CONFIG_URL"
expected-type="java.net.URL" />
<bean id="configUrl" class="org.springframework.core.io">
<property name="url" ref="configUrlResource" />
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<!--通过#来获取configUrl的具体值,并读取文件夹内的properties -->
<value>#{configUrl + '/ldap.properties'}</value>
<value>#{configUrl + '/config.properties'}</value>
</list>
</property>
</bean>
<!--其他使用方式举例,通过configUrl的get方法获取其他类型-->
#{configUrl.URI.toExternalForm()}
spel功能非常强大,可以参考:https://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html