SPRING IN ACTION 第4版笔记-第二章WIRING BEANS-006-当构造函数有集合时的注入
一.当构造函数有集合时,只能用<CONSTRUCTOR-ARG>,不能用C-NAMESPACE
二、
1.
1 package soundsystem.collections; 2 3 import java.util.List; 4 5 import soundsystem.CompactDisc; 6 7 public class BlankDisc implements CompactDisc { 8 9 private String title; 10 private String artist; 11 private List<String> tracks; 12 13 public BlankDisc(String title, String artist, List<String> tracks) { 14 this.title = title; 15 this.artist = artist; 16 this.tracks = tracks; 17 } 18 19 public void play() { 20 System.out.println("Playing " + title + " by " + artist); 21 for (String track : tracks) { 22 System.out.println("-Track: " + track); 23 } 24 } 25 26 }
(1)可以注入null,但运行会nullpointerException
1 <bean id="compactDisc" class="soundsystem.BlankDisc"> 2 <constructor-arg value="Sgt. Pepper's Lonely Hearts Club Band" /> 3 <constructor-arg value="The Beatles" /> 4 <constructor-arg><null/></constructor-arg> 5 </bean>
(2)注入list
<bean id="compactDisc" class="soundsystem.BlankDisc"> <constructor-arg value="Sgt. Pepper's Lonely Hearts Club Band" /> <constructor-arg value="The Beatles" /> <constructor-arg> <list> <value>Sgt. Pepper's Lonely Hearts Club Band</value> <value>With a Little Help from My Friends</value> <value>Lucy in the Sky with Diamonds</value> <value>Getting Better</value> <value>Fixing a Hole</value> <!-- ...other tracks omitted for brevity... --> </list> </constructor-arg>
(2)如果构造函数的集合参数的元素是对象,则用<ref>
public Discography(String artist, List<CompactDisc> cds) { ... }
<bean id="beatlesDiscography" class="soundsystem.Discography"> <constructor-arg value="The Beatles" /> <constructor-arg> <list> <ref bean="sgtPeppers" /> <ref bean="whiteAlbum" /> <ref bean="hardDaysNight" /> <ref bean="revolver" /> ... </list> </constructor-arg> </bean>
(3)也可以注入set
It makes sense to use <list> when wiring a constructor argument of type
java.util.List . Even so, you could also use the <set> element in the same way:
<bean id="compactDisc" class="soundsystem.BlankDisc"> <constructor-arg value="Sgt. Pepper's Lonely Hearts Club Band" /> <constructor-arg value="The Beatles" /> <constructor-arg> <set> <value>Sgt. Pepper's Lonely Hearts Club Band</value> <value>With a Little Help from My Friends</value> <value>Lucy in the Sky with Diamonds</value> <value>Getting Better</value> <value>Fixing a Hole</value> <!-- ...other tracks omitted for brevity... --> </set> </constructor-arg> </bean>
There’s little difference between <set> and <list> . The main difference is that when
Spring creates the collection to be wired, it will create it as either a java.util.Set or
a java.util.List . If it’s a Set , then any duplicate values will be discarded and the
ordering may not be honored. But in either case, either a <set> or a <list> can be
wired into a List , a Set , or even an array.
You can do anything you set your mind to, man!