简体   繁体   English

在Spring中将字符串数组注入bean

[英]Inject array of strings to a bean in Spring

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://            www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="test" class="com.Test">
        <constructor-arg>
            <list>
                <value>aa</value>
                <value>bb</value>
                <value>cc</value>
            </list>
        </constructor-arg>
    </bean>
</beans>

This is my current XML. 这是我目前的XML。 If only Test took a List - everything would be fine. 如果只有Test拿了一份清单 - 一切都会好的。

The problem is that Test takes an array of strings. 问题是Test需要一个字符串数组。

How to do it in Spring? 怎么在春天做?

You should use: 你应该使用:

<constructor-arg>
    <array>
        <value>aa</value>
        <value>bb</value>
        <value>cc</value>
    </array>
</constructor-arg>

An array can contain multiple inner bean, ref, collection, or value elements. 数组可以包含多个内部bean,ref,collection或value元素。 This configuration element will always result in an array, even when being defined eg as a value for a map with value type Object. 即使在被定义为例如值为Object类型的映射的值时,此配置元素也将始终生成数组。

Also you can specify a value type which you will be passing: 您还可以指定要传递的值类型:

<array value-type="java.lang.String">
  <value>aa</value>
  <value>bb</value>
  <value>cc</value>
</array>

value-type 值类型

The default Java type for nested values. 嵌套值的默认Java类型。 Must be a fully qualified class name. 必须是完全限定的类名。

instead of <list> use 而不是<list>使用

<array>
  <value>aa</value>
  <value>bb</value>
  <value>cc</value>
</array>

With Spring version 3.2.8 you can use 使用Spring版本3.2.8,您可以使用

<constructor-arg>
    <list>
        <value>aa</value>
        <value>bb</value>
        <value>cc</value>
    </list>
</constructor-arg>

without problems. 没有问题。

If the constructor has String[] as a parameter (which also includes String... ), you can provide a comma-separated list: 如果构造函数将String[]作为参数(也包括String... ),则可以提供以逗号分隔的列表:

<constructor-arg value="Hindustan Moters,Tata Moters,Ashoka Leyland"/>

This is notoriously used to instantiate eg H2 DB server as a bean. 众所周知,这用于将例如H2 DB服务器实例化为bean。 See eg here . 见例如这里

Not sure which version introduced that. 不确定引入了哪个版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM