Java examples on org.springframework
- How do I declare a bean in Spring application?
- How do I use InitializingBean and DisposableBean interfaces in Spring?
- How do I create beans through factory method?
- How do I initialize and destroy beans in Spring?
- How do I define bean scoping in Spring?
- How do I defaulting init-method and destroy method in Spring?
- How do I inject a bean through constructors?
- How do I inject collections using map element in Spring?
- How do I inject collections using list element in Spring?
- How do I inject into bean properties?
- How do I wire / inject a null value in Spring?
- How do I inject collections using set element in Spring?
- How do I inject collections properties in Spring?
- How do I wire properties with Spring's p namespace?
- How do I inject collections using props element in Spring?
- How do I define inner bean in Spring?
- How do I call static method using Spring EL?
- How do I inject beans, properties and methods using Spring EL?
- How do I handle or avoid null value in SpEL?
- How do I do math operations using Spring EL?
How do I inject collections using set element in Spring?
In this example you will see how to use the <set> element to wire a collection property of a bean. We will reuse the bean that we use in the previous example How do I inject collections using list element in Spring?.
The Album bean have a songs property that have a type of java.util.List. The <set> element doesn't have to be used with java.util.Set. It can be used to wire a java.util.List collection. It just mean the it cannot contains duplicate values in it, so the collection will only contains a unique values.
Here how we configure our Spring context:
The <set> configuration can bee seen in the album bean configuration. We set the songs property. Within this property element we use the <set> element. And then using the <ref> element we add some bean into the collection.
Create the following code to run it:
You'll see the following output in the screen. As you can see, although we set three beans into the songs property, the Album bean only contain a single song. This is because we use the <set> element to wire the collection. It doesn't allow duplicate values.
Album = Album{title='Please Please Me', year=1963,
songs=[Song{title='I Saw Her Standing There', writer='Beatles'}, null],
publisher={},
props={}}