<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<array>
<value>classpath:/settings.properties</value>
</array>
</property>
</bean>
<bean id="jedisSentinelPool" class="redis.clients.jedis.JedisSentinelPool">
<constructor-arg name="masterName" value="${redis.masterName}"></constructor-arg>
<constructor-arg name="sentinels">
<set>
<value>${redis.host.a}</value>
<value>${redis.host.b}</value>
<value>${redis.host.c}</value>
</set>
</constructor-arg>
<constructor-arg name="poolConfig">
<bean class="redis.clients.jedis.JedisPoolConfig"></bean>
</constructor-arg>
<constructor-arg name="timeout" value="2000"></constructor-arg>
<constructor-arg name="password" value="#{'${redis.password}'?:null}"></constructor-arg>
<constructor-arg name="database" value="${redis.number}"></constructor-arg>
</bean>
<bean id="jedisTemplate" class="com.tcl.account.utils.JedisTemplate">
<constructor-arg name="jedisPool" ref="jedisSentinelPool"></constructor-arg>
</bean>
settings.properties:
redis.masterName=mymaster
redis.password=
redis.number=0
#test
redis.host.a=127.0.0.1:26379
redis.host.b=127.0.0.1:26379
redis.host.c=127.0.0.1:26379
注意上面spring配置文件中password的赋值,若${redis.password}不为空便返回自身,否则返回null。
另外${redis.password}一定放在单引号内否则会被当做bean id,于是会报这样的错:
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'foobared' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'
at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:208)