一.当构造函数有集合时,只能用<CONSTRUCTOR-ARG>,不能用C-NAMESPACE
二、
1.
package soundsystem.collections; import java.util.List; import soundsystem.CompactDisc; public class BlankDisc implements CompactDisc { private String title;
private String artist;
private List<String> tracks; public BlankDisc(String title, String artist, List<String> tracks) {
this.title = title;
this.artist = artist;
this.tracks = tracks;
} public void play() {
System.out.println("Playing " + title + " by " + artist);
for (String track : tracks) {
System.out.println("-Track: " + track);
}
} }
(1)可以注入null,但运行会nullpointerException
<bean id="compactDisc" class="soundsystem.BlankDisc">
<constructor-arg value="Sgt. Pepper's Lonely Hearts Club Band" />
<constructor-arg value="The Beatles" />
<constructor-arg><null/></constructor-arg>
</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.