创造网站的最简单 软件是哪个,网页设计网站建设报告,辽宁网站推广的目的,泰安58目录 前言
回顾
注入集合
List与set集合
Map集合 前言
前面学习依赖注入时注入的都是对象#xff0c;这里记录注入的值为集合的情况
回顾 在注入的时候#xff0c;如果要注入的属性的值为字符串或基本数据类型#xff0c;用value即可#xff1b;如果要注入一个对象的…目录 前言
回顾
注入集合
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并且用对应的属性注入值给strcountb ?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdbean classcom.cc.Test.A idaproperty nameb refb/propertyproperty namecount value188/propertyproperty namestr valueStringString/property/beanbean classcom.cc.Test.B idb/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 version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdbean classcom.cc.Test.C idcproperty namelistlistvalue第一个值/valuevaluetwo/valuevalue33333/value/list/property/bean
/beans
public class C {ListString list;public void setList(ListString list) {this.list list;}public void showList(){System.out.println(list);}
} 当然list集合内不止可以存字符串也能存一个类的引用此时只需将list标签内的value改为ref即可 bean classcom.cc.Test.B idb/beanbean classcom.cc.Test.B idb1/beanbean classcom.cc.Test.B idb2/beanbean classcom.cc.Test.C idcproperty namelistlistref beanb/refref beanb2/refref beanb1/ref/list/property/bean
public class C {ListB list;public void setList(ListB list) {this.list list;}public void showList(){System.out.println(list);}
}同理set集合只需在配置文件中将list改为set即可这里就不做演示。 Map集合
Map集合与list和set略有不同因为它的值为key/value键值对。 bean classcom.cc.Test.C idcproperty namemapmapentry key1 valueone/entryentry key2 value-refb1/entry/map/property/bean