在注入spring bean 属性值的时候常常会用到list, 一般使用方式例如以下:

<bean id="testBean" class="com.mytest.TestBean">

    <property name="myList">

         <list>

             <value> 1 </value>

             <value> 2 </value>

         </list>

    </properties>

</bean>


可是假设将这个list的值通过el表达式从properties文件里获取,怎样做到,properties中存储的是键值对的数据。是不能正确存储列表数据的。仅仅能使用字符串切割成数组、列表的形式。至于字符串的切割能够自己来切割也能够使用现有的spEL。

1. properties 中的配置(逗号切割的字符串)

    spring xml properties split with comma for list_xml

2. bean的list属性

     spring xml properties split with comma for list_字符串切割_02

3. spring xml bean  注冊 属性值

spring xml properties split with comma for list_字符串_03

4. bean属性的setter 获取到了我们想要的结果

spring xml properties split with comma for list_字符串切割_04


-------------------------------------------------

先不要急着用,其它spring还提供了更好用的InlineList, 即以大括号计算, 如 "{'a','b','c'}"  , 所以还能够这样配置

xx.properties

imageDomains={'ezhe.com','gozap.com','chouti.com'}

spring-service.xml

<bean id="hostsService" class="com.gozap.ezhe.service.impl.HostsServiceImpl">
        <property name="imageDomains" value="#{${imageDomains}}" />
</bean>


-------------------------------------------------

另外,假设要注入List<Bean> 且使用properties 属性占位符来配置,应该怎么做?

org.springframework.expression.spel.standard.TokenKind

// ordered by priority - operands first
	LITERAL_INT, LITERAL_LONG, LITERAL_HEXINT, LITERAL_HEXLONG, LITERAL_STRING, LITERAL_REAL, LITERAL_REAL_FLOAT,
	LPAREN("("), RPAREN(")"), COMMA(","), IDENTIFIER,
	COLON(":"),HASH("#"),RSQUARE("]"), LSQUARE("["),
	LCURLY("{"),RCURLY("}"),
	DOT("."), PLUS("+"), STAR("*"),  MINUS("-"), SELECT_FIRST("^["), SELECT_LAST("$["), QMARK("?"), PROJECT("!["),
	DIV("/"), GE(">="), GT(">"), LE("<="), LT("<"), EQ("=="), NE("!="),
	MOD("%"), NOT("!"), ASSIGN("="), INSTANCEOF("instanceof"), MATCHES("matches"), BETWEEN("between"),
	SELECT("?["),   POWER("^"),
	ELVIS("?:"), SAFE_NAVI("?."), BEAN_REF("@"), SYMBOLIC_OR("||"), SYMBOLIC_AND("&&"), INC("++"), DEC("--")


这里能够看到有个BEAN_REF("@") 这个就是 spEL引用bean


<bean id="hostsService" class="com.gozap.ezhe.service.impl.HostsServiceImpl">
        <property name="imageDomains" value="#{${imageDomains}}" />
        <property name="daos" value="#{ {@demoDao, @adminDao}}" />
    </bean>

spring xml properties split with comma for list_字符串切割_05


--------------------------------------------------------------------------------------------------------------------------------------

以下简要分析一下 spEL 解析

整体思路就是: 使用字符串切割 将 目标对象(target)、运算符、函数、參数等,假设是函数在getValue时使用反射机制运行,并获取结果

spring xml properties split with comma for list_字符串_06spring xml properties split with comma for list_属性值_07spring xml properties split with comma for list_spring_08spring xml properties split with comma for list_spring_09spring xml properties split with comma for list_字符串切割_10spring xml properties split with comma for list_xml_11