最近忙公司系統的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