Java 类org.springframework.core.annotation.AnnotationAwareOrderComparator 实例源码

项目:spring-security-oauth2-boot    文件:ResourceServerTokenServicesConfiguration.java   
@Bean
public JwtAccessTokenConverter jwtTokenEnhancer() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    String keyValue = this.resource.getJwt().getKeyValue();
    if (!StringUtils.hasText(keyValue)) {
        keyValue = getKeyFromServer();
    }
    if (StringUtils.hasText(keyValue) && !keyValue.startsWith("-----BEGIN")) {
        converter.setSigningKey(keyValue);
    }
    if (keyValue != null) {
        converter.setVerifierKey(keyValue);
    }
    if (!CollectionUtils.isEmpty(this.configurers)) {
        AnnotationAwareOrderComparator.sort(this.configurers);
        for (JwtAccessTokenConverterConfigurer configurer : this.configurers) {
            configurer.configure(converter);
        }
    }
    return converter;
}
项目:spring-security-oauth2-boot    文件:DefaultUserInfoRestTemplateFactory.java   
@Override
public OAuth2RestTemplate getUserInfoRestTemplate() {
    if (this.oauth2RestTemplate == null) {
        this.oauth2RestTemplate = createOAuth2RestTemplate(
                this.details == null ? DEFAULT_RESOURCE_DETAILS : this.details);
        this.oauth2RestTemplate.getInterceptors()
                .add(new AcceptJsonRequestInterceptor());
        AuthorizationCodeAccessTokenProvider accessTokenProvider = new AuthorizationCodeAccessTokenProvider();
        accessTokenProvider.setTokenRequestEnhancer(new AcceptJsonRequestEnhancer());
        this.oauth2RestTemplate.setAccessTokenProvider(accessTokenProvider);
        if (!CollectionUtils.isEmpty(this.customizers)) {
            AnnotationAwareOrderComparator.sort(this.customizers);
            for (UserInfoRestTemplateCustomizer customizer : this.customizers) {
                customizer.customize(this.oauth2RestTemplate);
            }
        }
    }
    return this.oauth2RestTemplate;
}
项目:spring4-understanding    文件:SpringFactoriesLoader.java   
/**
 * Load and instantiate the factory implementations of the given type from
 * {@value #FACTORIES_RESOURCE_LOCATION}, using the given class loader.
 * <p>The returned factories are sorted in accordance with the {@link AnnotationAwareOrderComparator}.
 * <p>If a custom instantiation strategy is required, use {@link #loadFactoryNames}
 * to obtain all registered factory names.
 * @param factoryClass the interface or abstract class representing the factory
 * @param classLoader the ClassLoader to use for loading (can be {@code null} to use the default)
 * @see #loadFactoryNames
 * @throws IllegalArgumentException if any factory implementation class cannot
 * be loaded or if an error occurs while instantiating any factory
 */
public static <T> List<T> loadFactories(Class<T> factoryClass, ClassLoader classLoader) {
    Assert.notNull(factoryClass, "'factoryClass' must not be null");
    ClassLoader classLoaderToUse = classLoader;
    if (classLoaderToUse == null) {
        classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
    }
    List<String> factoryNames = loadFactoryNames(factoryClass, classLoaderToUse);
    if (logger.isTraceEnabled()) {
        logger.trace("Loaded [" + factoryClass.getName() + "] names: " + factoryNames);
    }
    List<T> result = new ArrayList<T>(factoryNames.size());
    for (String factoryName : factoryNames) {
        result.add(instantiateFactory(factoryName, factoryClass, classLoaderToUse));
    }
    AnnotationAwareOrderComparator.sort(result);
    return result;
}
项目:spring4-understanding    文件:TransactionSynchronizationManager.java   
/**
 * Return an unmodifiable snapshot list of all registered synchronizations
 * for the current thread.
 * @return unmodifiable List of TransactionSynchronization instances
 * @throws IllegalStateException if synchronization is not active
 * @see TransactionSynchronization
 */
public static List<TransactionSynchronization> getSynchronizations() throws IllegalStateException {
    Set<TransactionSynchronization> synchs = synchronizations.get();
    if (synchs == null) {
        throw new IllegalStateException("Transaction synchronization is not active");
    }
    // Return unmodifiable snapshot, to avoid ConcurrentModificationExceptions
    // while iterating and invoking synchronization callbacks that in turn
    // might register further synchronizations.
    if (synchs.isEmpty()) {
        return Collections.emptyList();
    }
    else {
        // Sort lazily here, not in registerSynchronization.
        List<TransactionSynchronization> sortedSynchs = new ArrayList<TransactionSynchronization>(synchs);
        AnnotationAwareOrderComparator.sort(sortedSynchs);
        return Collections.unmodifiableList(sortedSynchs);
    }
}
项目:spring4-understanding    文件:ResourceUrlProvider.java   
protected void detectResourceHandlers(ApplicationContext appContext) {
    logger.debug("Looking for resource handler mappings");

    Map<String, SimpleUrlHandlerMapping> map = appContext.getBeansOfType(SimpleUrlHandlerMapping.class);
    List<SimpleUrlHandlerMapping> handlerMappings = new ArrayList<SimpleUrlHandlerMapping>(map.values());
    AnnotationAwareOrderComparator.sort(handlerMappings);

    for (SimpleUrlHandlerMapping hm : handlerMappings) {
        for (String pattern : hm.getHandlerMap().keySet()) {
            Object handler = hm.getHandlerMap().get(pattern);
            if (handler instanceof ResourceHttpRequestHandler) {
                ResourceHttpRequestHandler resourceHandler = (ResourceHttpRequestHandler) handler;
                if (logger.isDebugEnabled()) {
                    logger.debug("Found resource handler mapping: URL pattern=\"" + pattern + "\", " +
                            "locations=" + resourceHandler.getLocations() + ", " +
                            "resolvers=" + resourceHandler.getResourceResolvers());
                }
                this.handlerMap.put(pattern, resourceHandler);
            }
        }
    }
}
项目:spring4-understanding    文件:ExceptionHandlerExceptionResolver.java   
private void initExceptionHandlerAdviceCache() {
    if (getApplicationContext() == null) {
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Looking for exception mappings: " + getApplicationContext());
    }

    List<ControllerAdviceBean> adviceBeans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext());
    AnnotationAwareOrderComparator.sort(adviceBeans);

    for (ControllerAdviceBean adviceBean : adviceBeans) {
        ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver(adviceBean.getBeanType());
        if (resolver.hasExceptionMappings()) {
            this.exceptionHandlerAdviceCache.put(adviceBean, resolver);
            logger.info("Detected @ExceptionHandler methods in " + adviceBean);
        }
        if (ResponseBodyAdvice.class.isAssignableFrom(adviceBean.getBeanType())) {
            this.responseBodyAdvice.add(adviceBean);
            logger.info("Detected ResponseBodyAdvice implementation in " + adviceBean);
        }
    }
}
项目:spring4-understanding    文件:AutowiredAnnotationBeanPostProcessorTests.java   
@Test
public void testConstructorResourceInjectionWithMultipleOrderedCandidates() {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    bf.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
    AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
    bpp.setBeanFactory(bf);
    bf.addBeanPostProcessor(bpp);
    bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ConstructorsResourceInjectionBean.class));
    TestBean tb = new TestBean();
    bf.registerSingleton("testBean", tb);
    FixedOrder2NestedTestBean ntb1 = new FixedOrder2NestedTestBean();
    bf.registerSingleton("nestedTestBean1", ntb1);
    FixedOrder1NestedTestBean ntb2 = new FixedOrder1NestedTestBean();
    bf.registerSingleton("nestedTestBean2", ntb2);

    ConstructorsResourceInjectionBean bean = (ConstructorsResourceInjectionBean) bf.getBean("annotatedBean");
    assertNull(bean.getTestBean3());
    assertSame(tb, bean.getTestBean4());
    assertEquals(2, bean.getNestedTestBeans().length);
    assertSame(ntb2, bean.getNestedTestBeans()[0]);
    assertSame(ntb1, bean.getNestedTestBeans()[1]);
    bf.destroySingletons();
}
项目:spring4-understanding    文件:AutowiredAnnotationBeanPostProcessorTests.java   
@Test
public void testConstructorResourceInjectionWithMultipleCandidatesAsOrderedCollection() {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    bf.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
    AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
    bpp.setBeanFactory(bf);
    bf.addBeanPostProcessor(bpp);
    bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(
            ConstructorsCollectionResourceInjectionBean.class));
    TestBean tb = new TestBean();
    bf.registerSingleton("testBean", tb);
    FixedOrder2NestedTestBean ntb1 = new FixedOrder2NestedTestBean();
    bf.registerSingleton("nestedTestBean1", ntb1);
    FixedOrder1NestedTestBean ntb2 = new FixedOrder1NestedTestBean();
    bf.registerSingleton("nestedTestBean2", ntb2);

    ConstructorsCollectionResourceInjectionBean bean = (ConstructorsCollectionResourceInjectionBean) bf.getBean("annotatedBean");
    assertNull(bean.getTestBean3());
    assertSame(tb, bean.getTestBean4());
    assertEquals(2, bean.getNestedTestBeans().size());
    assertSame(ntb2, bean.getNestedTestBeans().get(0));
    assertSame(ntb1, bean.getNestedTestBeans().get(1));
    bf.destroySingletons();
}
项目:leopard    文件:LeopardHandlerMapping.java   
@Override
protected void initApplicationContext() throws BeansException {
    // new Exception("initApplicationContext").printStackTrace();
    // 修改拦截器排序
    try {
        Field field = AbstractHandlerMapping.class.getDeclaredField("interceptors");
        field.setAccessible(true);
        @SuppressWarnings("unchecked")
        List<Object> interceptors = (List<Object>) field.get(this);
        AnnotationAwareOrderComparator.sort(interceptors);
        // System.out.println("interceptors:" + interceptors);
    }
    catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    super.initApplicationContext();
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:ServletContextInitializerBeans.java   
private <T> List<Entry<String, T>> getOrderedBeansOfType(
        ListableBeanFactory beanFactory, Class<T> type, Set<?> excludes) {
    List<Entry<String, T>> beans = new ArrayList<Entry<String, T>>();
    Comparator<Entry<String, T>> comparator = new Comparator<Entry<String, T>>() {

        @Override
        public int compare(Entry<String, T> o1, Entry<String, T> o2) {
            return AnnotationAwareOrderComparator.INSTANCE.compare(o1.getValue(),
                    o2.getValue());
        }

    };
    String[] names = beanFactory.getBeanNamesForType(type, true, false);
    Map<String, T> map = new LinkedHashMap<String, T>();
    for (String name : names) {
        if (!excludes.contains(name)) {
            T bean = beanFactory.getBean(name, type);
            if (!excludes.contains(bean)) {
                map.put(name, bean);
            }
        }
    }
    beans.addAll(map.entrySet());
    Collections.sort(beans, comparator);
    return beans;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:DelegatingApplicationListener.java   
@SuppressWarnings("unchecked")
private List<ApplicationListener<ApplicationEvent>> getListeners(
        ConfigurableEnvironment env) {
    String classNames = env.getProperty(PROPERTY_NAME);
    List<ApplicationListener<ApplicationEvent>> listeners = new ArrayList<ApplicationListener<ApplicationEvent>>();
    if (StringUtils.hasLength(classNames)) {
        for (String className : StringUtils.commaDelimitedListToSet(classNames)) {
            try {
                Class<?> clazz = ClassUtils.forName(className,
                        ClassUtils.getDefaultClassLoader());
                Assert.isAssignable(ApplicationListener.class, clazz, "class ["
                        + className + "] must implement ApplicationListener");
                listeners.add((ApplicationListener<ApplicationEvent>) BeanUtils
                        .instantiateClass(clazz));
            }
            catch (Exception ex) {
                throw new ApplicationContextException(
                        "Failed to load context listener class [" + className + "]",
                        ex);
            }
        }
    }
    AnnotationAwareOrderComparator.sort(listeners);
    return listeners;
}
项目:spring-boot-concourse    文件:WebClientAutoConfiguration.java   
@Bean
@ConditionalOnMissingBean
public RestTemplateBuilder restTemplateBuilder() {
    RestTemplateBuilder builder = new RestTemplateBuilder();
    HttpMessageConverters converters = this.messageConverters.getIfUnique();
    if (converters != null) {
        builder = builder.messageConverters(converters.getConverters());
    }
    List<RestTemplateCustomizer> customizers = this.restTemplateCustomizers
            .getIfAvailable();
    if (!CollectionUtils.isEmpty(customizers)) {
        customizers = new ArrayList<RestTemplateCustomizer>(customizers);
        AnnotationAwareOrderComparator.sort(customizers);
        builder = builder.customizers(customizers);
    }
    return builder;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:WebClientAutoConfiguration.java   
@Bean
@ConditionalOnMissingBean
public RestTemplateBuilder restTemplateBuilder() {
    RestTemplateBuilder builder = new RestTemplateBuilder();
    HttpMessageConverters converters = this.messageConverters.getIfUnique();
    if (converters != null) {
        builder = builder.messageConverters(converters.getConverters());
    }
    List<RestTemplateCustomizer> customizers = this.restTemplateCustomizers
            .getIfAvailable();
    if (!CollectionUtils.isEmpty(customizers)) {
        customizers = new ArrayList<RestTemplateCustomizer>(customizers);
        AnnotationAwareOrderComparator.sort(customizers);
        builder = builder.customizers(customizers);
    }
    return builder;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:UserInfoRestTemplateFactory.java   
public OAuth2RestTemplate getUserInfoRestTemplate() {
    if (this.template == null) {
        this.template = getTemplate(
                this.details == null ? DEFAULT_RESOURCE_DETAILS : this.details);
        this.template.getInterceptors().add(new AcceptJsonRequestInterceptor());
        AuthorizationCodeAccessTokenProvider accessTokenProvider = new AuthorizationCodeAccessTokenProvider();
        accessTokenProvider.setTokenRequestEnhancer(new AcceptJsonRequestEnhancer());
        this.template.setAccessTokenProvider(accessTokenProvider);
        if (!CollectionUtils.isEmpty(this.customizers)) {
            AnnotationAwareOrderComparator.sort(this.customizers);
            for (UserInfoRestTemplateCustomizer customizer : this.customizers) {
                customizer.customize(this.template);
            }
        }
    }
    return this.template;
}
项目:spring-cloud-gateway    文件:RouteDefinitionRouteLocator.java   
private List<GatewayFilter> getFilters(RouteDefinition routeDefinition) {
    List<GatewayFilter> filters = new ArrayList<>();

    //TODO: support option to apply defaults after route specific filters?
    if (!this.gatewayProperties.getDefaultFilters().isEmpty()) {
        filters.addAll(loadGatewayFilters("defaultFilters",
                this.gatewayProperties.getDefaultFilters()));
    }

    if (!routeDefinition.getFilters().isEmpty()) {
        filters.addAll(loadGatewayFilters(routeDefinition.getId(), routeDefinition.getFilters()));
    }

    AnnotationAwareOrderComparator.sort(filters);
    return filters;
}
项目:spring    文件:SpringFactoriesLoader.java   
/**
 * Load and instantiate the factory implementations of the given type from
 * {@value #FACTORIES_RESOURCE_LOCATION}, using the given class loader.
 * <p>The returned factories are sorted in accordance with the {@link AnnotationAwareOrderComparator}.
 * <p>If a custom instantiation strategy is required, use {@link #loadFactoryNames}
 * to obtain all registered factory names.
 * @param factoryClass the interface or abstract class representing the factory
 * @param classLoader the ClassLoader to use for loading (can be {@code null} to use the default)
 * @see #loadFactoryNames
 * @throws IllegalArgumentException if any factory implementation class cannot
 * be loaded or if an error occurs while instantiating any factory
 */
public static <T> List<T> loadFactories(Class<T> factoryClass, ClassLoader classLoader) {
    Assert.notNull(factoryClass, "'factoryClass' must not be null");
    ClassLoader classLoaderToUse = classLoader;
    if (classLoaderToUse == null) {
        classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
    }
    List<String> factoryNames = loadFactoryNames(factoryClass, classLoaderToUse);
    if (logger.isTraceEnabled()) {
        logger.trace("Loaded [" + factoryClass.getName() + "] names: " + factoryNames);
    }
    List<T> result = new ArrayList<T>(factoryNames.size());
    for (String factoryName : factoryNames) {
        result.add(instantiateFactory(factoryName, factoryClass, classLoaderToUse));
    }
    AnnotationAwareOrderComparator.sort(result);
    return result;
}
项目:spring-boot-concourse    文件:ServletContextInitializerBeans.java   
private <T> List<Entry<String, T>> getOrderedBeansOfType(
        ListableBeanFactory beanFactory, Class<T> type, Set<?> excludes) {
    List<Entry<String, T>> beans = new ArrayList<Entry<String, T>>();
    Comparator<Entry<String, T>> comparator = new Comparator<Entry<String, T>>() {

        @Override
        public int compare(Entry<String, T> o1, Entry<String, T> o2) {
            return AnnotationAwareOrderComparator.INSTANCE.compare(o1.getValue(),
                    o2.getValue());
        }

    };
    String[] names = beanFactory.getBeanNamesForType(type, true, false);
    Map<String, T> map = new LinkedHashMap<String, T>();
    for (String name : names) {
        if (!excludes.contains(name)) {
            T bean = beanFactory.getBean(name, type);
            if (!excludes.contains(bean)) {
                map.put(name, bean);
            }
        }
    }
    beans.addAll(map.entrySet());
    Collections.sort(beans, comparator);
    return beans;
}
项目:spring-boot-concourse    文件:DelegatingApplicationListener.java   
@SuppressWarnings("unchecked")
private List<ApplicationListener<ApplicationEvent>> getListeners(
        ConfigurableEnvironment env) {
    String classNames = env.getProperty(PROPERTY_NAME);
    List<ApplicationListener<ApplicationEvent>> listeners = new ArrayList<ApplicationListener<ApplicationEvent>>();
    if (StringUtils.hasLength(classNames)) {
        for (String className : StringUtils.commaDelimitedListToSet(classNames)) {
            try {
                Class<?> clazz = ClassUtils.forName(className,
                        ClassUtils.getDefaultClassLoader());
                Assert.isAssignable(ApplicationListener.class, clazz, "class ["
                        + className + "] must implement ApplicationListener");
                listeners.add((ApplicationListener<ApplicationEvent>) BeanUtils
                        .instantiateClass(clazz));
            }
            catch (Exception ex) {
                throw new ApplicationContextException(
                        "Failed to load context listener class [" + className + "]",
                        ex);
            }
        }
    }
    AnnotationAwareOrderComparator.sort(listeners);
    return listeners;
}
项目:cas-5.1.0    文件:DefaultWebApplicationResponseBuilderLocator.java   
@Override
public ResponseBuilder locate(final WebApplicationService service) {
    final Map<String, ResponseBuilder> beans = applicationContext.getBeansOfType(ResponseBuilder.class, false, true);
    final List<ResponseBuilder> builders = beans.values().stream().collect(Collectors.toList());
    AnnotationAwareOrderComparator.sortIfNecessary(builders);
    return builders.stream().filter(r -> r.supports(service)).findFirst().orElse(null);
}
项目:configx    文件:ConfigContext.java   
/**
 * 注册配置项预处理器
 *
 * @return
 */
private void registerConfigItemPostProcessors() {
    List<ConfigItemPostProcessor> configItemPostProcessors = new ArrayList<>();
    configItemPostProcessors.addAll(applicationContext.getBeansOfType(ConfigItemPostProcessor.class).values());
    AnnotationAwareOrderComparator.sort(configItemPostProcessors);

    this.configItemPostProcessors.addAll(configItemPostProcessors);
}
项目:configx    文件:ConfigContext.java   
/**
 * 注册配置监听器
 */
private void registerConfigWatchers() {
    List<ConfigWatcher> watchers = new ArrayList<>();
    watchers.addAll(applicationContext.getBeansOfType(ConfigWatcher.class).values());
    AnnotationAwareOrderComparator.sort(watchers);

    // 如果没有配置任何监听器,则启动一个默认的轮询监听器
    if (CollectionUtils.isEmpty(watchers)) {
        ConfigWatcher defaultConfigWatcher = createDefaultConfigWatcher();
        watchers.add(defaultConfigWatcher);
    }

    this.configWatchers.addAll(watchers);
}
项目:spring-boot-data-source-decorator    文件:DataSourceDecoratorBeanPostProcessor.java   
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof DataSource && !getDataSourceDecoratorProperties().getExcludeBeans().contains(beanName)) {
        DataSource dataSource = (DataSource) bean;
        DataSource decoratedDataSource = dataSource;
        Map<String, DataSourceDecorator> decorators = new LinkedHashMap<>();
        applicationContext.getBeansOfType(DataSourceDecorator.class)
                .entrySet()
                .stream()
                .sorted(Entry.comparingByValue(AnnotationAwareOrderComparator.INSTANCE))
                .forEach(entry -> decorators.put(entry.getKey(), entry.getValue()));
        List<DataSourceDecorationStage> decoratedDataSourceChainEntries = new ArrayList<>();
        for (Entry<String, DataSourceDecorator> decoratorEntry : decorators.entrySet()) {
            String decoratorBeanName = decoratorEntry.getKey();
            DataSourceDecorator decorator = decoratorEntry.getValue();

            DataSource dataSourceBeforeDecorating = decoratedDataSource;
            decoratedDataSource = Objects.requireNonNull(decorator.decorate(beanName, decoratedDataSource),
                    "DataSourceDecorator (" + decoratorBeanName + ", " + decorator + ") should not return null");

            if (dataSourceBeforeDecorating != decoratedDataSource) {
                decoratedDataSourceChainEntries.add(0, new DataSourceDecorationStage(decoratorBeanName, decorator, decoratedDataSource));
            }
        }
        if (dataSource != decoratedDataSource) {
            ProxyFactory factory = new ProxyFactory(bean);
            factory.setProxyTargetClass(true);
            factory.addInterface(DecoratedDataSource.class);
            factory.addAdvice(new DataSourceDecoratorInterceptor(beanName, dataSource, decoratedDataSource, decoratedDataSourceChainEntries));
            return factory.getProxy();
        }
    }
    return bean;
}
项目:holon-jaxrs    文件:ResteasyAutoConfiguration.java   
private void customize() {
    if (this.customizers != null) {
        AnnotationAwareOrderComparator.sort(this.customizers);
        for (ResteasyConfigCustomizer customizer : this.customizers) {
            customizer.customize(this.config);
        }
    }
}
项目:holon-jaxrs    文件:JaxrsClientBuilderAutoConfiguration.java   
@Bean
@ConditionalOnMissingBean
public JaxrsClientBuilder jaxrsClientBuilder() {
    DefaultJaxrsClientBuilder builder = new DefaultJaxrsClientBuilder();
    JaxrsClientBuilderFactory factory = this.clientBuilderFactory.getIfUnique();
    if (factory != null) {
        builder.setFactory(factory);
    }
    List<JaxrsClientCustomizer> customizers = this.customizers.getIfAvailable();
    if (customizers != null && !customizers.isEmpty()) {
        AnnotationAwareOrderComparator.sort(customizers);
        customizers.forEach(c -> builder.addCustomizer(c));
    }
    return builder;
}
项目:lams    文件:SpringServletContainerInitializer.java   
/**
 * Delegate the {@code ServletContext} to any {@link WebApplicationInitializer}
 * implementations present on the application classpath.
 *
 * <p>Because this class declares @{@code HandlesTypes(WebApplicationInitializer.class)},
 * Servlet 3.0+ containers will automatically scan the classpath for implementations
 * of Spring's {@code WebApplicationInitializer} interface and provide the set of all
 * such types to the {@code webAppInitializerClasses} parameter of this method.
 *
 * <p>If no {@code WebApplicationInitializer} implementations are found on the
 * classpath, this method is effectively a no-op. An INFO-level log message will be
 * issued notifying the user that the {@code ServletContainerInitializer} has indeed
 * been invoked but that no {@code WebApplicationInitializer} implementations were
 * found.
 *
 * <p>Assuming that one or more {@code WebApplicationInitializer} types are detected,
 * they will be instantiated (and <em>sorted</em> if the @{@link
 * org.springframework.core.annotation.Order @Order} annotation is present or
 * the {@link org.springframework.core.Ordered Ordered} interface has been
 * implemented). Then the {@link WebApplicationInitializer#onStartup(ServletContext)}
 * method will be invoked on each instance, delegating the {@code ServletContext} such
 * that each instance may register and configure servlets such as Spring's
 * {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener},
 * or any other Servlet API componentry such as filters.
 *
 * @param webAppInitializerClasses all implementations of
 * {@link WebApplicationInitializer} found on the application classpath
 * @param servletContext the servlet context to be initialized
 * @see WebApplicationInitializer#onStartup(ServletContext)
 * @see AnnotationAwareOrderComparator
 */
@Override
public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
        throws ServletException {

    List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();

    if (webAppInitializerClasses != null) {
        for (Class<?> waiClass : webAppInitializerClasses) {
            // Be defensive: Some servlet containers provide us with invalid classes,
            // no matter what @HandlesTypes says...
            if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
                    WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
                try {
                    initializers.add((WebApplicationInitializer) waiClass.newInstance());
                }
                catch (Throwable ex) {
                    throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
                }
            }
        }
    }

    if (initializers.isEmpty()) {
        servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
        return;
    }

    AnnotationAwareOrderComparator.sort(initializers);
    servletContext.log("Spring WebApplicationInitializers detected on classpath: " + initializers);

    for (WebApplicationInitializer initializer : initializers) {
        initializer.onStartup(servletContext);
    }
}
项目:lams    文件:ContextLoader.java   
/**
 * Customize the {@link ConfigurableWebApplicationContext} created by this
 * ContextLoader after config locations have been supplied to the context
 * but before the context is <em>refreshed</em>.
 * <p>The default implementation {@linkplain #determineContextInitializerClasses(ServletContext)
 * determines} what (if any) context initializer classes have been specified through
 * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and
 * {@linkplain ApplicationContextInitializer#initialize invokes each} with the
 * given web application context.
 * <p>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or marked with @{@link
 * org.springframework.core.annotation.Order Order} will be sorted appropriately.
 * @param sc the current servlet context
 * @param wac the newly created application context
 * @see #createWebApplicationContext(ServletContext, ApplicationContext)
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 */
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
    List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
            determineContextInitializerClasses(sc);
    if (initializerClasses.isEmpty()) {
        // no ApplicationContextInitializers have been declared -> nothing to do
        return;
    }

    ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerInstances =
            new ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>>();

    for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
        Class<?> initializerContextClass =
                GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
        if (initializerContextClass != null) {
            Assert.isAssignable(initializerContextClass, wac.getClass(), String.format(
                    "Could not add context initializer [%s] since its generic parameter [%s] " +
                    "is not assignable from the type of application context used by this " +
                    "context loader [%s]: ", initializerClass.getName(), initializerContextClass.getName(),
                    wac.getClass().getName()));
        }
        initializerInstances.add(BeanUtils.instantiateClass(initializerClass));
    }

    AnnotationAwareOrderComparator.sort(initializerInstances);
    for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : initializerInstances) {
        initializer.initialize(wac);
    }
}
项目:odata-spring-boot-starter    文件:ODataServlet.java   
/**
 * Constructor.
 *
 * @param edmProviderResolvers
 *     Entity Data Model provider resolvers
 * @param processors
 *     processors
 */
public ODataServlet(
    List<CsdlEdmProviderResolver> edmProviderResolvers, List<Processor> processors) {

  this.edmProviderResolvers = new ArrayList<>(edmProviderResolvers);
  this.edmProviderResolvers.sort(AnnotationAwareOrderComparator.INSTANCE);

  this.processors = processors;
}
项目:lodsve-framework    文件:LodsveBannerPrinter.java   
@Override
public void onStartup(Set<Class<?>> classSet, ServletContext servletContext) throws ServletException {
    if (classSet == null) {
        servletContext.log("No Banner in classpath to print!");
        return;
    }

    List<Banner> banners = new ArrayList<>(classSet.size());
    for (Class<?> clazz : classSet) {
        if (!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()) && Banner.class.isAssignableFrom(clazz)) {
            try {
                banners.add((Banner) clazz.newInstance());
            } catch (Throwable ex) {
                throw new ServletException("Failed to instantiate Banner class", ex);
            }
        }
    }

    if (banners.isEmpty()) {
        servletContext.log("No Banner in classpath to print!");
        return;
    }

    AnnotationAwareOrderComparator.sort(banners);
    servletContext.log("banners detected on classpath: " + banners);

    for (Banner banner : banners) {
        banner.print(System.out);
    }
}
项目:spring4-understanding    文件:AspectJProxyFactory.java   
/**
 * Add all {@link Advisor Advisors} from the supplied {@link MetadataAwareAspectInstanceFactory}
 * to the current chain. Exposes any special purpose {@link Advisor Advisors} if needed.
 * @see AspectJProxyUtils#makeAdvisorChainAspectJCapableIfNecessary(List)
 */
private void addAdvisorsFromAspectInstanceFactory(MetadataAwareAspectInstanceFactory instanceFactory) {
    List<Advisor> advisors = this.aspectFactory.getAdvisors(instanceFactory);
    advisors = AopUtils.findAdvisorsThatCanApply(advisors, getTargetClass());
    AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(advisors);
    AnnotationAwareOrderComparator.sort(advisors);
    addAdvisors(advisors);
}
项目:spring-boot-concourse    文件:SpringApplication.java   
private void callRunners(ApplicationContext context, ApplicationArguments args) {
    List<Object> runners = new ArrayList<Object>();
    runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
    runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
    AnnotationAwareOrderComparator.sort(runners);
    for (Object runner : new LinkedHashSet<Object>(runners)) {
        if (runner instanceof ApplicationRunner) {
            callRunner((ApplicationRunner) runner, args);
        }
        if (runner instanceof CommandLineRunner) {
            callRunner((CommandLineRunner) runner, args);
        }
    }
}
项目:spring4-understanding    文件:DispatcherPortlet.java   
/**
 * Initialize the HandlerMappings used by this class.
 * <p>If no HandlerMapping beans are defined in the BeanFactory
 * for this namespace, we default to PortletModeHandlerMapping.
 */
private void initHandlerMappings(ApplicationContext context) {
    this.handlerMappings = null;

    if (this.detectAllHandlerMappings) {
        // Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
        Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
                context, HandlerMapping.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
            // We keep HandlerMappings in sorted order.
            AnnotationAwareOrderComparator.sort(this.handlerMappings);
        }
    }
    else {
        try {
            HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
            this.handlerMappings = Collections.singletonList(hm);
        }
        catch (NoSuchBeanDefinitionException ex) {
            // Ignore, we'll add a default HandlerMapping later.
        }
    }

    // Ensure we have at least one HandlerMapping, by registering
    // a default HandlerMapping if no other mappings are found.
    if (this.handlerMappings == null) {
        this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
        if (logger.isDebugEnabled()) {
            logger.debug("No HandlerMappings found in portlet '" + getPortletName() + "': using default");
        }
    }
}
项目:spring-boot-concourse    文件:DelegatingApplicationContextInitializer.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
private void applyInitializers(ConfigurableApplicationContext context,
        List<ApplicationContextInitializer<?>> initializers) {
    Collections.sort(initializers, new AnnotationAwareOrderComparator());
    for (ApplicationContextInitializer initializer : initializers) {
        initializer.initialize(context);
    }
}
项目:spring4-understanding    文件:DispatcherPortlet.java   
/**
 * Initialize the HandlerExceptionResolver used by this class.
 * <p>If no bean is defined with the given name in the BeanFactory
 * for this namespace, we default to no exception resolver.
 */
private void initHandlerExceptionResolvers(ApplicationContext context) {
    this.handlerExceptionResolvers = null;

    if (this.detectAllHandlerExceptionResolvers) {
        // Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.
        Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
                context, HandlerExceptionResolver.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(matchingBeans.values());
            // We keep HandlerExceptionResolvers in sorted order.
            AnnotationAwareOrderComparator.sort(this.handlerExceptionResolvers);
        }
    }
    else {
        try {
            HandlerExceptionResolver her = context.getBean(
                    HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
            this.handlerExceptionResolvers = Collections.singletonList(her);
        }
        catch (NoSuchBeanDefinitionException ex) {
            // Ignore, no HandlerExceptionResolver is fine too.
        }
    }

    // Just for consistency, check for default HandlerExceptionResolvers...
    // There aren't any in usual scenarios.
    if (this.handlerExceptionResolvers == null) {
        this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class);
        if (logger.isDebugEnabled()) {
            logger.debug("No HandlerExceptionResolvers found in portlet '" + getPortletName() + "': using default");
        }
    }
}
项目:spring-boot-concourse    文件:EndpointWebMvcChildContextConfiguration.java   
private List<HandlerMapping> extractMappings() {
    List<HandlerMapping> list = new ArrayList<HandlerMapping>();
    list.addAll(this.beanFactory.getBeansOfType(HandlerMapping.class).values());
    list.remove(this);
    AnnotationAwareOrderComparator.sort(list);
    return list;
}
项目:spring4-understanding    文件:EventListenerMethodProcessor.java   
/**
 * Return the {@link EventListenerFactory} instances to use to handle
 * {@link EventListener} annotated methods.
 */
protected List<EventListenerFactory> getEventListenerFactories() {
    Map<String, EventListenerFactory> beans = this.applicationContext.getBeansOfType(EventListenerFactory.class);
    List<EventListenerFactory> allFactories = new ArrayList<EventListenerFactory>(beans.values());
    AnnotationAwareOrderComparator.sort(allFactories);
    return allFactories;
}
项目:spring4-understanding    文件:ContentNegotiatingViewResolver.java   
@Override
protected void initServletContext(ServletContext servletContext) {
    Collection<ViewResolver> matchingBeans =
            BeanFactoryUtils.beansOfTypeIncludingAncestors(getApplicationContext(), ViewResolver.class).values();
    if (this.viewResolvers == null) {
        this.viewResolvers = new ArrayList<ViewResolver>(matchingBeans.size());
        for (ViewResolver viewResolver : matchingBeans) {
            if (this != viewResolver) {
                this.viewResolvers.add(viewResolver);
            }
        }
    }
    else {
        for (int i = 0; i < viewResolvers.size(); i++) {
            if (matchingBeans.contains(viewResolvers.get(i))) {
                continue;
            }
            String name = viewResolvers.get(i).getClass().getName() + i;
            getApplicationContext().getAutowireCapableBeanFactory().initializeBean(viewResolvers.get(i), name);
        }

    }
    if (this.viewResolvers.isEmpty()) {
        logger.warn("Did not find any ViewResolvers to delegate to; please configure them using the " +
                "'viewResolvers' property on the ContentNegotiatingViewResolver");
    }
    AnnotationAwareOrderComparator.sort(this.viewResolvers);
    this.cnmFactoryBean.setServletContext(servletContext);
}
项目:spring-boot-concourse    文件:ResourceServerTokenServicesConfiguration.java   
@Bean
public JwtAccessTokenConverter jwtTokenEnhancer() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    String keyValue = this.resource.getJwt().getKeyValue();
    if (!StringUtils.hasText(keyValue)) {
        try {
            keyValue = getKeyFromServer();
        }
        catch (ResourceAccessException ex) {
            logger.warn("Failed to fetch token key (you may need to refresh "
                    + "when the auth server is back)");
        }
    }
    if (StringUtils.hasText(keyValue) && !keyValue.startsWith("-----BEGIN")) {
        converter.setSigningKey(keyValue);
    }
    if (keyValue != null) {
        converter.setVerifierKey(keyValue);
    }
    if (!CollectionUtils.isEmpty(this.configurers)) {
        AnnotationAwareOrderComparator.sort(this.configurers);
        for (JwtAccessTokenConverterConfigurer configurer : this.configurers) {
            configurer.configure(converter);
        }
    }
    return converter;
}
项目:spring4-understanding    文件:DispatcherServlet.java   
/**
 * Initialize the HandlerAdapters used by this class.
 * <p>If no HandlerAdapter beans are defined in the BeanFactory for this namespace,
 * we default to SimpleControllerHandlerAdapter.
 */
private void initHandlerAdapters(ApplicationContext context) {
    this.handlerAdapters = null;

    if (this.detectAllHandlerAdapters) {
        // Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.
        Map<String, HandlerAdapter> matchingBeans =
                BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.handlerAdapters = new ArrayList<HandlerAdapter>(matchingBeans.values());
            // We keep HandlerAdapters in sorted order.
            AnnotationAwareOrderComparator.sort(this.handlerAdapters);
        }
    }
    else {
        try {
            HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
            this.handlerAdapters = Collections.singletonList(ha);
        }
        catch (NoSuchBeanDefinitionException ex) {
            // Ignore, we'll add a default HandlerAdapter later.
        }
    }

    // Ensure we have at least some HandlerAdapters, by registering
    // default HandlerAdapters if no other adapters are found.
    if (this.handlerAdapters == null) {
        this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);
        if (logger.isDebugEnabled()) {
            logger.debug("No HandlerAdapters found in servlet '" + getServletName() + "': using default");
        }
    }
}
项目:spring4-understanding    文件:DispatcherServlet.java   
/**
 * Initialize the HandlerExceptionResolver used by this class.
 * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
 * we default to no exception resolver.
 */
private void initHandlerExceptionResolvers(ApplicationContext context) {
    this.handlerExceptionResolvers = null;

    if (this.detectAllHandlerExceptionResolvers) {
        // Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.
        Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils
                .beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(matchingBeans.values());
            // We keep HandlerExceptionResolvers in sorted order.
            AnnotationAwareOrderComparator.sort(this.handlerExceptionResolvers);
        }
    }
    else {
        try {
            HandlerExceptionResolver her =
                    context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
            this.handlerExceptionResolvers = Collections.singletonList(her);
        }
        catch (NoSuchBeanDefinitionException ex) {
            // Ignore, no HandlerExceptionResolver is fine too.
        }
    }

    // Ensure we have at least some HandlerExceptionResolvers, by registering
    // default HandlerExceptionResolvers if no other resolvers are found.
    if (this.handlerExceptionResolvers == null) {
        this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class);
        if (logger.isDebugEnabled()) {
            logger.debug("No HandlerExceptionResolvers found in servlet '" + getServletName() + "': using default");
        }
    }
}
项目:spring4-understanding    文件:DispatcherServlet.java   
/**
 * Initialize the ViewResolvers used by this class.
 * <p>If no ViewResolver beans are defined in the BeanFactory for this
 * namespace, we default to InternalResourceViewResolver.
 */
private void initViewResolvers(ApplicationContext context) {
    this.viewResolvers = null;

    if (this.detectAllViewResolvers) {
        // Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
        Map<String, ViewResolver> matchingBeans =
                BeanFactoryUtils.beansOfTypeIncludingAncestors(context, ViewResolver.class, true, false);
        if (!matchingBeans.isEmpty()) {
            this.viewResolvers = new ArrayList<ViewResolver>(matchingBeans.values());
            // We keep ViewResolvers in sorted order.
            AnnotationAwareOrderComparator.sort(this.viewResolvers);
        }
    }
    else {
        try {
            ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);
            this.viewResolvers = Collections.singletonList(vr);
        }
        catch (NoSuchBeanDefinitionException ex) {
            // Ignore, we'll add a default ViewResolver later.
        }
    }

    // Ensure we have at least one ViewResolver, by registering
    // a default ViewResolver if no other resolvers are found.
    if (this.viewResolvers == null) {
        this.viewResolvers = getDefaultStrategies(context, ViewResolver.class);
        if (logger.isDebugEnabled()) {
            logger.debug("No ViewResolvers found in servlet '" + getServletName() + "': using default");
        }
    }
}