Spring依赖注入不同类型的数据
目录
前言
回顾
注入集合
List与set集合
Map集合
前言
前面学习依赖注入时注入的都是对象,这里记录注入的值为集合的情况
回顾
在注入的时候,如果要注入的属性的值为字符串或基本数据类型,用value即可;如果要注入一个对象的引用,则使用ref属性。
用一段代码进行演示:
准备一个类B作为要注入的类
public class B {public void useB(){System.out.println("B对象成功注入.......");} }
在类A中写入对象类型的属性B,基本数据类型count,字符串类型str;并且提供对应的set方法
public class A {B b;int count;String str;public void setStr(String str) {this.str = str;}public void setB(B b) {this.b = b;}public void setCount(int count) {this.count = count;}public void text(){System.out.println("即将使用属性B的方法");b.useB();System.out.println("注入的基本数据类型的值为"+count);System.out.println("注入的字符串为"+str);} }
接着在spring的配置文件中配置bean,并且用对应的属性注入值给str,count,b
<?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 class="com.cc.Test.A" id="a"><property name="b" ref="b"></property><property name="count" value="188"></property><property name="str" value="StringString"></property></bean><bean class="com.cc.Test.B" id="b"></bean> </beans>
最后编写一个测试类
public class Main {public static void main(String[] args) {ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("test.xml");A bean = (A) app.getBean("a");bean.text();} }
测试结果:可以看到对应的值已经成功注入!!
注入集合
List与set集合
要注入list集合,只需在spring的配置文件进行简单的修改,使用list标签,标签内使用很多value标签注入值:
<?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 class="com.cc.Test.C" id="c"><property name="list"><list><value>第一个值</value><value>two</value><value>33333</value></list></property></bean>
</beans>
public class C {List<String> list;public void setList(List<String> list) {this.list = list;}public void showList(){System.out.println(list);}
}
当然,list集合内不止可以存字符串,也能存一个类的引用,此时只需将list标签内的value改为ref即可:
<bean class="com.cc.Test.B" id="b"></bean><bean class="com.cc.Test.B" id="b1"></bean><bean class="com.cc.Test.B" id="b2"></bean><bean class="com.cc.Test.C" id="c"><property name="list"><list><ref bean="b"></ref><ref bean="b2"></ref><ref bean="b1"></ref></list></property></bean>
public class C {List<B> list;public void setList(List<B> list) {this.list = list;}public void showList(){System.out.println(list);}
}
同理,set集合只需在配置文件中将<list>改为<set>即可,这里就不做演示。
Map集合
Map集合与list和set略有不同,因为它的值为key/value键值对。
<bean class="com.cc.Test.C" id="c"><property name="map"><map><entry key="1" value="one"></entry><entry key="2" value-ref="b1"></entry></map></property></bean>