Spring初始化集合
时间:2020-02-23 14:35:41 来源:igfitidea点击:
之前我们已经了解如何通过属性的值标记或者ref标记初始化任何字符串或者引用。
在本教程中,我们将看到如何在Spring中初始化任何集合。
在Eclipse IDE中配置Spring,请参阅Hello World示例
1.Country.java:
这是一个简单的pojo类,其中有一些属性,所以这里有一个国家的名称和名单。
在package org.igi.javapostssforlarearning中创建country.java .Copy内容到Country.java之后。
package org.igi.javapostsforlearning;
import java.util.List;
public class Country {
String countryName;
List listOfStates;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public List getListOfStates() {
return listOfStates;
}
public void setListOfStates(List listOfStates) {
this.listOfStates = listOfStates;
}
public void printListOfStates()
{
System.out.println("Some of states in Netherlands are:");
for(String state:listOfStates)
{
System.out.println(state);
}
}
}
2.ApplicationContext.xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="CountryBean" class="org.igi.javapostsforlearning.Country">
<property name="listOfStates">
<list>
<value>Maharastra</value>
<value>Madhya Pradesh</value>
<value>Rajasthan</value>
</list>
</property>
</bean>
</beans>
这里用于初始化Collection(列表)例如:listofstates属性的国家类,我们使用了list标记。
在标记中,我们可以有标签或者标记以添加列表中的值。
3.InitializingCollectionSmain.java.
此类包含主函数.Create initializingcollectionsmain.java在package org.igi.javapostsfor learearning .copy之后内容到初始化CollectionSmain.java之后
package org.igi.javapostsforlearning;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class InitializingCollectionsMain{
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Country countryObj = (Country) appContext.getBean("CountryBean");
countryObj.printListOfStates();
}
}
我们可以在此处注意到,我们在此处使用ClassPathxmlApplicationContext来获取bean。
有多种方法来获取beans.in Hello World示例我们已使用XMLBeanFactory来获取beans。
4.运行
当我们将运行上面的应用程序时,输出如下
Some of states in Netherlands are: Maharastra Madhya Pradesh Rajasthan

