目录
一、介绍
二、数组与集合注入(XML形式)
总结
一、介绍
1.其他文章的介绍,如有不懂可以结合起来看
快速入门使用spring详细步骤(介绍、导入依赖、第一个简单程序)_云边的快乐猫的博客-CSDN博客
spring的注入(set注入、构造器注入)_云边的快乐猫的博客-CSDN博客
2.使用spring的时候,遇到要数组注入或者集合注入,那该怎么做呢?请看如下的步骤
二、数组与集合注入(XML形式)
1.建立一个类,里面存放数组与集合,还要获取注入返回的方法
![](https://img-blog.csdnimg.cn/1e9f77d916d74cdcbe19cb9ae18a9dae.png)
package com.spring6.bean;
import java.util.*;
public class Book {
//数组
private int[] array;
//list集合
private List list;
//set集合
private Set set;
//map集合
private Map map;
//属性集合
private Properties properties;
//生成的set方法
public void setArray(int[] array) {
this.array = array;
}
public void setList(List list) {
this.list = list;
}
public void setSet(Set set) {
this.set = set;
}
public void setMap(Map map) {
this.map = map;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
//创建一个方法去调用spring注入的结果
public void listBean(){
System.out.println("这是数组的"+Arrays.toString(array));
System.out.println("这是list的"+list);
System.out.println("这是Set的"+set);
System.out.println("这是Map的"+map);
System.out.println("这是properties的"+properties);
}
}
2.新建一个spring的xm文件,在bean标签里面使用对应的方式添加注入数据进去数组或者集合里面
ps: 点击resources,然后快捷键Alt+insert--->XML配置文件--->spring配置
![](https://img-blog.csdnimg.cn/1df3928b4c454d4abf72ff12fb515b94.png)
1
11
我是list集合
22
我是list集合
22
敲代码
还是敲代码
3.建立一个测试类去运行本次注入的输出结果
![](https://img-blog.csdnimg.cn/b7e6e9e3888c4e8c9c42dc9adaa320f5.png)
package com.spring6.text;
import com.spring6.bean.Book;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class springTText {
@Test
public void TT(){
//1.半固定写法,扫描spring的xml文件(不固定的是要扫描的是哪个xml文件)
ApplicationContext applicationContext =new ClassPathXmlApplicationContext("spring.xml");
//2.半固定写法,获取spring里面要进行运行的类(不固定的是括号里面的,name为:要运行类的id,后面跟着的是要运行的类.class)
Book bookBean = applicationContext.getBean("BookBean", Book.class);
//3.上面自定义名.要运行类的方法
bookBean.listBean();
}
}
4.运行结果
![](https://img-blog.csdnimg.cn/d549c56e53b04db18362103e602ac947.png)
总结
这个数组和集合的注入也很简单,只需要在xml文件里面写入对应的注入标签就好了,建立类和测试类还是和原来一样
|