我正在使用弹簧 3.2.2。我在通过 spring 的 byType 自动装配模式自动装配集合时遇到问题。我创建了以下示例。
豆定义:
package com.springaction.testmultidimesionalcollection;
import java.util.ArrayList;
/**
* @author jinesh
*
*/
public class Address {
ArrayList<Country> country;
public ArrayList<Country> getCountry() {
return country;
}
/**
* @param country the country to set
*/
public void setCountry(ArrayList<Country> country) {
this.country = country;
}
}
下面是spring配置文件testmultidimensionalcollection.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean id="addressMiddleEast" class="com.springaction.testmultidimesionalcollection.Address" autowire="byType">
</bean>
<bean id="countryChina" class="com.springaction.testmultidimesionalcollection.Country">
<property name="countryName" value="China" />
</bean>
<bean id="countryIndia" class="com.springaction.testmultidimesionalcollection.Country">
<property name="countryName" value="India" />
</bean>
<bean id="countryAus" class="com.springaction.testmultidimesionalcollection.Country">
<property name="countryName" value="Australia" />
</bean>
<bean id="middeastcountryQuatar" class="com.springaction.testmultidimesionalcollection.Country">
<property name="countryName" value="Quatar" />
</bean>
<bean id="middeastcountryIsrael" class="com.springaction.testmultidimesionalcollection.Country">
<property name="countryName" value="Israel" />
</bean>
<bean id="middeastcountryYemen" class="com.springaction.testmultidimesionalcollection.Country">
<property name="countryName" value="Yemen" />
</bean>
</beans>
在这里,我在 Address 类中有强类型集合。所以国家的所有元素都应该添加到国家属性数组列表中,但是当我执行下面的代码时,我得到空指针异常。
package com.springaction.testmultidimesionalcollection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author jinesh
*
*/
public class TestMultiDimensionalMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext("com/springaction/testmultidimesionalcollection/testmultidimensionalcollection.xml");
Address addrs=(Address)context.getBean("addressMiddleEast");
System.out.println("address size:" + addrs.getCountry().size());
}
}
我不明白,为什么spring不能自动检测国家bean并将它们添加到地址bean的数组列表属性中?我错过了配置中的某些内容吗?