Spring 4 offers an array of new features. As with all releases, some of the new features are big and impactful. Others are tiny but helpful.
Autowiring Collections
One of the new small features in Spring 4 is the ability to use @Order with autowiring. There has always been the ability to have Spring automatically collect all beans of a given type and inject them into a collection or array. Since Spring 2.5, this was most commonly accomplished by annotation as shown below (injecting an Employee and Customer bean into the List of people on Organization).
package com.intertech; import org.springframework.stereotype.Component; @Component public class Employee implements Person { }
package com.intertech; import org.springframework.stereotype.Component; @Component public class Customer implements Person { }
package com.intertech; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class Organization { @Autowired List<Person> people; public String toString() { return people.toString(); } }
In this case, however, there is no order associated to the list of beans added to the Organization’s people. You could use XML to define the beans and then, in most cases, the beans will be added to the people list in the order they are defined in the XML. However, you may be trying to avoid or minimize the amount of XML in your applications. Also, most developers know better than to depend on the order of the elements in an XML to preserve any order at runtime. Well, Spring 4 provides a solution.
@Order and autowiring
The @Order annotation has been in the Spring Framework for some time (since 2.0 per the documentation). It has always been used to provide order to components like AspectJ aspects. Now, in Spring 4, it can order beans wired to an ordered collection. Add the @Order annotation to the bean classes and specify the order precedence (as shown below). Lower values have higher priority – meaning they will appear first in the collection.
package com.intertech; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(value=1) public class Employee implements Person { }
package com.intertech; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(value=2) public class Customer implements Person { }
Results:
[com.intertech.Employee@a52728a, com.intertech.Customer@2addc751]
BTW – if you prefer not to use @Order, you can implement the org.springframework.core.Ordered interface in the element classes (Customer and Employee in the example above) instead.