目录
一、介绍
1.其他文章的介绍,如有不懂可以结合起来看
2.使用spring的时候,遇到要数组注入或者集合注入,那该怎么做呢?请看如下的步骤
二、数组与集合注入(XML形式)
1.建立一个类,里面存放数组与集合,还要获取注入返回的方法
package com.spring6.bean;
import java.util.*;
public class Book {
//数组
private int[] array;
//list集合
private List<String> list;
//set集合
private Set<String> set;
//map集合
private Map<String,String> map;
//属性集合
private Properties properties;
//生成的set方法
public void setArray(int[] array) {
this.array = array;
}
public void setList(List<String> list) {
this.list = list;
}
public void setSet(Set<String> set) {
this.set = set;
}
public void setMap(Map<String, String> 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配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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">
<bean id="BookBean" class="com.spring6.bean.Book">
<!-- array数组 -->
<property name="array">
<array>
<value>1</value>
<value>11</value>
</array>
</property>
<!-- list集合注入 -->
<property name="list">
<list>
<value>我是list集合</value>
<value>22</value>
</list>
</property>
<!--set集合注入 -->
<property name="set">
<set>
<value>我是list集合</value>
<value>22</value>
</set>
</property>
<!--map集合注入 -->
<property name="map">
<map>
<entry key="hobby" value="eat"/>
<entry key="hobby2" value="sleep"/>
</map>
</property>
<!-- Properties集合注入 -->
<property name="properties">
<props>
<prop key="hobby"> 敲代码</prop>
<prop key="hobby2"> 还是敲代码</prop>
</props>
</property>
</bean>
</beans>
3.建立一个测试类去运行本次注入的输出结果
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.运行结果
总结
这个数组和集合的注入也很简单,只需要在xml文件里面写入对应的注入标签就好了,建立类和测试类还是和原来一样
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/112603.html