Spring 集合注入 [ Collection Injection ] (一)

2014-11-24 11:49:45 · 作者: · 浏览: 30

对于简单数据类型(byte,char,short,int,float,double,long )或者String的注入,一般只需写入标签即可。比如:


[html]

或者


[html]

simpleva lue


simpleva lue

或者p模式


如果需要注入的是集合(list,set,map,pros),那该怎么做呢?

如果集合的泛型是简单数据类型,比如 List,可以这样实现:


[html]


student1
student2
...



student1
student2
...


如果集合的泛型是引用类型,比如List,可以利用内部bean实现

[java]










......











......


下面是一个具体例子:

省份类:


[java]
public class Province {

private String name; // 省份名称
private long population; // 人口
private List cities; // 城市列表
private List officials; // 官员
// 标准setter 和 getter 以及 toString方法省略
}

public class Province {

private String name; // 省份名称
private long population; // 人口
private List cities; // 城市列表
private List officials; // 官员
// 标准setter 和 getter 以及 toString方法省略
}

[java]
public class Official {

private String name;
private String title;
private String age;
// 省略setter 和 getter 以及 toString方法
}

public class Official {

private String name;
private String title;
private String age;
// 省略setter 和 getter 以及 toString方法
}
bean配置文件:


[html]
< xml version="1.0" encoding="UTF-8" >
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">



四川




成都
绵阳
德阳
攀枝花
遂宁
江油






















< xml version="1.0" encoding="UTF-8" >
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">



四川




成都
绵阳
德阳
攀枝花
遂宁
江油























运行它:


[java]
public class App {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"SpringConfig.xml"});
Province siChuan = (Province) context.getBean("sichuan");
System.out.println(siChuan);
}
}

public class App {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"SpringConfig.xml"});
Province siChuan = (Province) context.getBean("sichuan");
System.out.println(siChuan);
}
}
打印输出:


[plain