Skip to content

Autowiring should support ordered collection driven by Order annotation or Ordered interface [SPR-5574] #10245

Closed

Description

@spring-projects-issues

Roman Pichlík opened SPR-5574 and commented

Let suppose that there are beans of a given type T and these beans are marked by interface Ordered or annotation Order. It does make really sense to preserve their order according to Ordered/Order marker if they are collected. See following code for illustration.

@Component
@Order(value=1)
public class BusinessServiceA implements BusinessService{}

@Component
@Order(value=2)
public class BusinessServiceB implements BusinessService{}

@Component
public class ServiceRegistry {
@Autowired
public List<BusinessService> services;
}

assertThat(services.get(0).getClass(), is(BusinessServiceA.class));
assertThat(services.get(1).getClass(), is(BusinessServiceB.class));


Issue Links:

Referenced from: commits 4a9af23

15 votes, 15 watchers

Activity

  1. spring-projects-issues commented on Jul 11, 2011

    @spring-projects-issues
    CollaboratorAuthor

    David Erickson commented

    Would love to see this implemented, have run into use cases needing this!!

  2. spring-projects-issues commented on May 27, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Martin Frey commented

    Here is a version that I have implemented at the time I needed that feature in an ExtendedBeanFactory:

    @Override
    protected Object doResolveDependency(DependencyDescriptor descriptor,
              Class<?> type, String beanName, Set<String> autowiredBeanNames,
              TypeConverter typeConverter) throws BeansException {
         Object result = super.doResolveDependency(descriptor, type, beanName,
                   autowiredBeanNames, typeConverter);
         if (result != null && descriptor.getField() != null) {
              if (descriptor.getField().isAnnotationPresent(OrderedWired.class)) {
                   if (type.isArray()) {
                            Object[] resultArray = (Object[]) result;
                            if (log.isDebugEnabled()) {
                                     log.debug("Sorting results for {}.{}", descriptor
                                                       .getField().getDeclaringClass(), descriptor
                                                       .getDependencyName());
                            }
                            Arrays.sort(resultArray,
                                              AnnotationAwareOrderComparator.INSTANCE);
                            return resultArray;
                   } else if (List.class.isAssignableFrom(type)) {
                            List<?> resultList = (List<?>) super.doResolveDependency(
                                              descriptor, type, beanName, autowiredBeanNames,
                                              typeConverter);
                            if (log.isDebugEnabled()) {
                                     log.debug("Sorting results for {}.{}", descriptor
                                                       .getField().getDeclaringClass(), descriptor
                                                       .getDependencyName());
                            }
                            Collections.sort(resultList,
                                              AnnotationAwareOrderComparator.INSTANCE);
                            return resultList;
                   }
              }
         }
         return result;
    }
    

    And this would be wired like this at the moment:

    @Autowired
    @OrderedWired
    private List<DataInitializer> dataInitializers;
    
  3. spring-projects-issues commented on Aug 22, 2013

    @spring-projects-issues
    CollaboratorAuthor

    Juergen Hoeller commented

    Finally implemented as a core feature for 4.0: However, not in the BeanFactory's resolveDependency itself but rather in AutowiredAnnotationBeanPostProcessor, in order to limit its applicability to @Autowired/@Inject. Programmatic callers of resolveDependency can call AnnotationAwareOrderComparator.sortIfNecessary(...) as they see fit.

    Juergen

  4. spring-projects-issues commented on Jan 6, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Ittai Zeidman commented

    @Juergen,
    Any chance this will be backported to 3.2.x?

  5. spring-projects-issues commented on Jan 7, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Juergen Hoeller commented

    I'm afraid not, since 3.2.x is in maintenance mode already... with the upcoming 3.2.7 being the last planned release in that line, just fixing a few remaining bugs.

    That said, is there anything preventing you from upgrading to the 4.0 line? The upcoming 4.0.1 fixes all known regressions from 3.2.x, so it should be a very smooth upgrade... as long as the minimal system requirements are met (see https://github.com/spring-projects/spring-framework/wiki/Migrating-from-earlier-versions-of-the-spring-framework).

    Juergen

  6. spring-projects-issues commented on Jan 7, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Martin Frey commented

    As this will not be backported i add here the steps i took to implement it in an ExtendedBeanFactory for 3.2 at the time. (Upgrading from Spring 3.2 to 4.0 was a breeze by the way! 1h of work. Thanks for that :) )

    -> I removed the OrderedWired Annotation in this code, so arrays and collections are always sorted.

    1. create ExtendedBeanFactory:
        public class ExtendedBeanFactory extends DefaultListableBeanFactory {
            private static final Logger log = LoggerFactory.getLogger(ExtendedBeanFactory.class);
    
            public ExtendedBeanFactory() {
                super();
            }
    
            public ExtendedBeanFactory(BeanFactory parentBeanFactory) {
                super(parentBeanFactory);
            }
    
            @Override
            protected Object doResolveDependency(DependencyDescriptor descriptor, Class<?> type, String beanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
                Object result = super.doResolveDependency(descriptor, type, beanName, autowiredBeanNames, typeConverter);
                if (result != null) {
                    if (type.isArray()) {
                        Object[] resultArray = (Object[]) result;
                        if (log.isDebugEnabled()) {
                            log.debug("Sorting results for {}.{}", descriptor.getField().getDeclaringClass(), //$NON-NLS-1$
                                    descriptor.getDependencyName());
                        }
                        Arrays.sort(resultArray, AnnotationAwareOrderComparator.INSTANCE);
                        return resultArray;
                    } else if (List.class.isAssignableFrom(type)) {
                        List<?> resultList = (List<?>) super.doResolveDependency(descriptor, type, beanName, autowiredBeanNames,
                                typeConverter);
                        if (log.isDebugEnabled()) {
                            log.debug("Sorting results for {}.{}", descriptor.getField().getDeclaringClass(), //$NON-NLS-1$
                                    descriptor.getDependencyName());
                        }
                        Collections.sort(resultList, AnnotationAwareOrderComparator.INSTANCE);
                        return resultList;
                    }
                }
                return result;
            }
        }
    
    1. create ExtendedXmlWebApplicationContext:
        public class ExtendedXmlWebApplicationContext extends XmlWebApplicationContext {
    
            @Override
            protected DefaultListableBeanFactory createBeanFactory() {
                return new ExtendedBeanFactory(getInternalParentBeanFactory());
            }
    
        }
    
    1. create ExtendedDispatcherServlet
        public class ExtendedDispatcherServlet extends DispatcherServlet {
    
            public ExtendedDispatcherServlet() {
                super();
                setContextClass(ExtendedXmlWebApplicationContext.class);
            }
    
            public ExtendedDispatcherServlet(WebApplicationContext webApplicationContext) {
                super(webApplicationContext);
                setContextClass(ExtendedXmlWebApplicationContext.class);
            }
    
        }
    
    1. declare it in web.xml
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.....ExtendedXmlWebApplicationContext</param-value>
    </context-param>
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.....ExtendedDispatcherServlet</servlet-class>
    </servlet>
    

    For test integration this was a bit more tricky as i needed to override the AbstractDelegatingSmartContextLoader. If this code is desired I can post this too.

    As said, upgrading to 4.0 was a simple excercise, so if you can upgrade i would go for that solution.

  7. spring-projects-issues commented on Jan 15, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Donnchadh O Donnabhain commented

    Anybody using Spring WebFlow would be blocked from upgrading to Spring 4.0 until SWF 2.3.3, which includes SWF-1600, is released.

  8. spring-projects-issues commented on Aug 11, 2014

    @spring-projects-issues
    CollaboratorAuthor

    sorin commented

    If I want to sort a list of beans of type A for example, I don't think it's enough to implement Ordered interface, I move to 4.0.0 but the getOrder method it's not call, I have to declare bean of type BeanPostProcessor in order to be call getOrder method from OrderComparator class.

    I's normal this behavior ?

    thanks
    Sorin

  9. spring-projects-issues commented on Aug 11, 2014

    @spring-projects-issues
    CollaboratorAuthor

    Stéphane Nicoll commented

    Hi,

    This issue has been closed. If you have a question, please raise it on StackOverflow with the #spring tag. What you are describing should work out-of-the box: both Ordered implementations and annotated class with @Order are used to order the collection to auto wire.

    Thanks.

  10. added
    type: enhancement
    in: core
    has: votes-jira
    on Jan 11, 2019
  11. added this to the 4.0 M3 milestone on Jan 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

has: votes-jirain: coretype: enhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions