spring xml properties split with comma for list

时间:2022-10-11 08:12:32

在注入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

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

2. bean的list属性

spring xml properties split with comma for list

3. spring xml bean  注冊 属性值

spring xml properties split with comma for list

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

spring xml properties split with comma for list

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

先不要急着用,其它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

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

以下简要分析一下 spEL 解析

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

spring xml properties split with comma for listspring xml properties split with comma for list

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">spring xml properties split with comma for listspring xml properties split with comma for listspring xml properties split with comma for listspring xml properties split with comma for list