Class ApplicationContextUtils


  • public final class ApplicationContextUtils
    extends Object
    Utility functions related to application contexts.
    Since:
    10.0
    Author:
    Petru Galanton
    • Method Detail

      • beansWithAnnotationIncludingAncestors

        public static Map<String,​Object> beansWithAnnotationIncludingAncestors​(org.springframework.context.ApplicationContext ctx,
                                                                                     Class<? extends Annotation> annotationType)
                                                                              throws org.springframework.beans.BeansException
        Returns all beans annotated with the specified annotation type defined in the specified application context and all its ancestor contexts.

        If both a descendant and an ancestor context contain a bean with the same id and both are annotated with the specified annotation type, the bean in the descendant context takes precedence.

        Parameters:
        ctx - the starting application context
        annotationType - the annotation type to search for
        Returns:
        a map with bean ids and beans
        Throws:
        org.springframework.beans.BeansException - if a bean could not be created
      • getNonScopedTargetBeansWithAnnotation

        public static Map<String,​Object> getNonScopedTargetBeansWithAnnotation​(org.springframework.context.ApplicationContext ctx,
                                                                                     Class<? extends Annotation> annotationType)
        Helper method to find all non scoped target beans whose Class has the supplied Annotation type, returning a Map of bean names with corresponding bean instances.

        ListableBeanFactory.getBeans* methods are able to look up any beans, even both the proxy and the target variant of a scoped bean. The advised workaround is either check getBeanDefinition(candidateName).isAutowireCandidate() and skip non-autowire beans that way or simply check for beanName.startsWith(ScopedProxyUtils.TARGET_NAME_PREFIX) (which is a supported way of detecting generated scoped target beans).

        See also:
        • AQ-10369 Filter scoped target beans when using getBeansWithAnnotation()
        • https://jira.spring.io/browse/SPR-14887
        Parameters:
        ctx - the application context to get the annotated beans from
        annotationType - the type of annotation to look for
        Returns:
        a Map with the matching beans, containing the bean names as keys and the corresponding bean instances as values