如何在spring bean中注入一个int数组

如何在spring bean中注入一个int数组

问题描述:

我有一个整数列表,例如1、2、3、4、5、6、7、8、9、10

I have a list of integers like 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

我想将其用作POJO中的整数数组.

I want to use it as an integer array in my POJO.

但是,我不想在类中使用它,而是希望将其外部化到属性文件中,然后将其作为类的属性插入到xml中.

However, I do not want it inside my class, but want to externalize it into the properties file and then inject it in my xml as a property of the class.

该怎么做?

感谢阅读!

有一种这样的放置方法:

There's a way to put like this:

<beans:bean id="myBean" class="MyClass">
  <beans:property name="myIntArray" >
    <beans:list>
      <beans:value>1</beans:value>
      <beans:value>2</beans:value>
      <beans:value>3</beans:value>
   </beans:list>
  </beans:property>
</beans:bean>

但是由于您需要从属性文件中读取这些值,因此找不到从属性文件中读取的方法:-(

But as you require these values to be read from a properties file,Icouldn't find a way to read from properties file :-(

但是我对此有一个难看的解决方法.将您的班级更改为以下内容:

But I have an ugly fix for it. Change your class to something like this:

    Class MyCLass
    {
        private Integer[] myIntArray;
        private String[] myIntArrayStr;

        public Integer[] getMyIntArray(){
            return this.myIntArray;
        }
        public void setMyIntArray(Integer[] intArray){
            this.myIntArray=intArray;
        }
        public void setMyIntArrayStr(String[] myIntArrayStr) {
           this.myIntArrayStr = myIntArrayStr;
           //we are going to read the values as a string array and set out integer array inside this setter
           int i=0;
           Integer[] myInts = new Integer[myIntArrayStr.length];
           for(String s: myIntArrayStr){
               myInts[i]=Integer.parseInt(s);
               i++;
           }
           setMyIntArray(ints);
       }
   }

在xml中编写如下:

<beans:bean id="myBean" class="MyClass">
      <beans:property name="myIntArrayStr">
       <beans:value>
        ${myvalues} <!-- this is gonna come from properties file as previously was -->
       </beans:value>
      </beans:property>

    </beans:bean>

希望这会有所帮助.