Spring:将字符串列表的所有值注入到bean中

Mom*_*omo 1 java spring java-8

我想使用具有 xml 配置的属性文件注入列表值。

        <property name="headerOfFile">
            <util:list id="headerOfFileList" value-type="java.lang.String">
                <value>headerA</value>
                <value>headerB</value>
            </util:list>
        </property>
Run Code Online (Sandbox Code Playgroud)

我想使用 xml bean 配置通过属性文件注入我的列表值。我知道使用 Java 我们可以这样做:

@Value("#{'${my.list.of.header.strings}'.split(',')}") 
private List<String> headerOfFile;
Run Code Online (Sandbox Code Playgroud)

假设我的属性文件已正确加载,如下所示:

my.list.of.header.strings=headerA,headerB
Run Code Online (Sandbox Code Playgroud)

但我的要求是使用带有属性文件的 xml beans 来完成此操作。

Sot*_*lis 6

Spring EL 也可以在 XML 中工作。value您所需要的只是在您的 bean 的属性中提供相同的表达式property

<property name="headerOfFile" value="#{'${my.list.of.header.strings}'.split(',')}">
</property>
Run Code Online (Sandbox Code Playgroud)

这假设您启用了适当的属性解析配置

<context:property-placeholder location="your_config.properties" />
<context:annotation-config />
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要split表达式中的 the 。Spring 已经支持将逗号分隔值转换为开箱即用的列表/数组。你可以只使用

<property name="headerOfFile" value="${my.list.of.header.strings}">
</property>
Run Code Online (Sandbox Code Playgroud)

您将需要DefaultConversionService由以下人员提供

<bean id="conversionService"
    class="org.springframework.context.support.ConversionServiceFactoryBean" />
Run Code Online (Sandbox Code Playgroud)