Search in sources :

Example 6 with ClassPathBeanDefinitionScanner

use of org.springframework.context.annotation.ClassPathBeanDefinitionScanner in project spring-framework by spring-projects.

the class ClassPathBeanDefinitionScannerScopeIntegrationTests method createContext.

private ApplicationContext createContext(ScopedProxyMode scopedProxyMode) {
    GenericWebApplicationContext context = new GenericWebApplicationContext();
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
    scanner.setIncludeAnnotationConfig(false);
    scanner.setBeanNameGenerator((definition, registry) -> definition.getScope());
    scanner.setScopedProxyMode(scopedProxyMode);
    // Scan twice in order to find errors in the bean definition compatibility check.
    scanner.scan(getClass().getPackage().getName());
    scanner.scan(getClass().getPackage().getName());
    context.refresh();
    return context;
}
Also used : ClassPathBeanDefinitionScanner(org.springframework.context.annotation.ClassPathBeanDefinitionScanner) GenericWebApplicationContext(org.springframework.web.context.support.GenericWebApplicationContext)

Example 7 with ClassPathBeanDefinitionScanner

use of org.springframework.context.annotation.ClassPathBeanDefinitionScanner in project spring-framework by spring-projects.

the class AnnotationConfigWebApplicationContext method loadBeanDefinitions.

/**
 * Register a {@link org.springframework.beans.factory.config.BeanDefinition} for
 * any classes specified by {@link #register(Class...)} and scan any packages
 * specified by {@link #scan(String...)}.
 * <p>For any values specified by {@link #setConfigLocation(String)} or
 * {@link #setConfigLocations(String[])}, attempt first to load each location as a
 * class, registering a {@code BeanDefinition} if class loading is successful,
 * and if class loading fails (i.e. a {@code ClassNotFoundException} is raised),
 * assume the value is a package and attempt to scan it for component classes.
 * <p>Enables the default set of annotation configuration post processors, such that
 * {@code @Autowired}, {@code @Required}, and associated annotations can be used.
 * <p>Configuration class bean definitions are registered with generated bean
 * definition names unless the {@code value} attribute is provided to the stereotype
 * annotation.
 * @param beanFactory the bean factory to load bean definitions into
 * @see #register(Class...)
 * @see #scan(String...)
 * @see #setConfigLocation(String)
 * @see #setConfigLocations(String[])
 * @see AnnotatedBeanDefinitionReader
 * @see ClassPathBeanDefinitionScanner
 */
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
    AnnotatedBeanDefinitionReader reader = getAnnotatedBeanDefinitionReader(beanFactory);
    ClassPathBeanDefinitionScanner scanner = getClassPathBeanDefinitionScanner(beanFactory);
    BeanNameGenerator beanNameGenerator = getBeanNameGenerator();
    if (beanNameGenerator != null) {
        reader.setBeanNameGenerator(beanNameGenerator);
        scanner.setBeanNameGenerator(beanNameGenerator);
        beanFactory.registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
    }
    ScopeMetadataResolver scopeMetadataResolver = getScopeMetadataResolver();
    if (scopeMetadataResolver != null) {
        reader.setScopeMetadataResolver(scopeMetadataResolver);
        scanner.setScopeMetadataResolver(scopeMetadataResolver);
    }
    if (!this.componentClasses.isEmpty()) {
        if (logger.isDebugEnabled()) {
            logger.debug("Registering component classes: [" + StringUtils.collectionToCommaDelimitedString(this.componentClasses) + "]");
        }
        reader.register(ClassUtils.toClassArray(this.componentClasses));
    }
    if (!this.basePackages.isEmpty()) {
        if (logger.isDebugEnabled()) {
            logger.debug("Scanning base packages: [" + StringUtils.collectionToCommaDelimitedString(this.basePackages) + "]");
        }
        scanner.scan(StringUtils.toStringArray(this.basePackages));
    }
    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
        for (String configLocation : configLocations) {
            try {
                Class<?> clazz = ClassUtils.forName(configLocation, getClassLoader());
                if (logger.isTraceEnabled()) {
                    logger.trace("Registering [" + configLocation + "]");
                }
                reader.register(clazz);
            } catch (ClassNotFoundException ex) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Could not load class for config location [" + configLocation + "] - trying package scan. " + ex);
                }
                int count = scanner.scan(configLocation);
                if (count == 0 && logger.isDebugEnabled()) {
                    logger.debug("No component classes found for specified class/package [" + configLocation + "]");
                }
            }
        }
    }
}
Also used : ClassPathBeanDefinitionScanner(org.springframework.context.annotation.ClassPathBeanDefinitionScanner) BeanNameGenerator(org.springframework.beans.factory.support.BeanNameGenerator) ScopeMetadataResolver(org.springframework.context.annotation.ScopeMetadataResolver) AnnotatedBeanDefinitionReader(org.springframework.context.annotation.AnnotatedBeanDefinitionReader)

Example 8 with ClassPathBeanDefinitionScanner

use of org.springframework.context.annotation.ClassPathBeanDefinitionScanner in project spring-framework by spring-projects.

the class Spr8510Tests method genericWAC.

/**
 * Ensure that ContextLoaderListener and GenericWebApplicationContext interact nicely.
 */
@Test
public void genericWAC() {
    GenericWebApplicationContext ctx = new GenericWebApplicationContext();
    ContextLoaderListener cll = new ContextLoaderListener(ctx);
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
    scanner.scan("bogus.pkg");
    cll.contextInitialized(new ServletContextEvent(new MockServletContext()));
}
Also used : ClassPathBeanDefinitionScanner(org.springframework.context.annotation.ClassPathBeanDefinitionScanner) ContextLoaderListener(org.springframework.web.context.ContextLoaderListener) ServletContextEvent(jakarta.servlet.ServletContextEvent) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) Test(org.junit.jupiter.api.Test)

Example 9 with ClassPathBeanDefinitionScanner

use of org.springframework.context.annotation.ClassPathBeanDefinitionScanner in project grails-core by grails.

the class ClosureClassIgnoringComponentScanBeanDefinitionParser method createScanner.

@Override
protected ClassPathBeanDefinitionScanner createScanner(XmlReaderContext readerContext, boolean useDefaultFilters) {
    final ClassPathBeanDefinitionScanner scanner = super.createScanner(readerContext, useDefaultFilters);
    BeanDefinitionRegistry beanDefinitionRegistry = readerContext.getRegistry();
    GrailsPluginManager pluginManager = null;
    if (beanDefinitionRegistry instanceof HierarchicalBeanFactory) {
        HierarchicalBeanFactory beanFactory = (HierarchicalBeanFactory) beanDefinitionRegistry;
        BeanFactory parent = beanFactory.getParentBeanFactory();
        if (parent != null && parent.containsBean(GrailsPluginManager.BEAN_NAME)) {
            pluginManager = parent.getBean(GrailsPluginManager.BEAN_NAME, GrailsPluginManager.class);
        }
    }
    if (pluginManager != null) {
        List<TypeFilter> typeFilters = pluginManager.getTypeFilters();
        for (TypeFilter typeFilter : typeFilters) {
            scanner.addIncludeFilter(typeFilter);
        }
    }
    return scanner;
}
Also used : ClassPathBeanDefinitionScanner(org.springframework.context.annotation.ClassPathBeanDefinitionScanner) GrailsPluginManager(grails.plugins.GrailsPluginManager) HierarchicalBeanFactory(org.springframework.beans.factory.HierarchicalBeanFactory) BeanFactory(org.springframework.beans.factory.BeanFactory) BeanDefinitionRegistry(org.springframework.beans.factory.support.BeanDefinitionRegistry) TypeFilter(org.springframework.core.type.filter.TypeFilter) HierarchicalBeanFactory(org.springframework.beans.factory.HierarchicalBeanFactory)

Example 10 with ClassPathBeanDefinitionScanner

use of org.springframework.context.annotation.ClassPathBeanDefinitionScanner in project grails-core by grails.

the class ClosureClassIgnoringComponentScanBeanDefinitionParser method configureScanner.

@Override
protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) {
    final ClassPathBeanDefinitionScanner scanner = super.configureScanner(parserContext, element);
    final ResourceLoader originalResourceLoader = parserContext.getReaderContext().getResourceLoader();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Scanning only this classloader:" + originalResourceLoader.getClassLoader());
    }
    ResourceLoader parentOnlyResourceLoader;
    try {
        parentOnlyResourceLoader = new ResourceLoader() {

            ClassLoader parentOnlyGetResourcesClassLoader = new ParentOnlyGetResourcesClassLoader(originalResourceLoader.getClassLoader());

            public Resource getResource(String location) {
                return originalResourceLoader.getResource(location);
            }

            public ClassLoader getClassLoader() {
                return parentOnlyGetResourcesClassLoader;
            }
        };
    } catch (Throwable t) {
        // restrictive classloading environment, use the original
        parentOnlyResourceLoader = originalResourceLoader;
    }
    final PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(parentOnlyResourceLoader) {

        @Override
        protected Resource[] findAllClassPathResources(String location) throws IOException {
            Set<Resource> result = new LinkedHashSet<Resource>(16);
            if (BuildSettings.CLASSES_DIR != null) {
                @SuppressWarnings("unused") URL classesDir = BuildSettings.CLASSES_DIR.toURI().toURL();
                // only scan classes from project classes directory
                String path = location;
                if (path.startsWith("/")) {
                    path = path.substring(1);
                }
                Enumeration<URL> resourceUrls = getClassLoader().getResources(path);
                while (resourceUrls.hasMoreElements()) {
                    URL url = resourceUrls.nextElement();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Scanning URL " + url.toExternalForm() + " while searching for '" + location + "'");
                    }
                    /*
                    if (!warDeployed && classesDir!= null && url.equals(classesDir)) {
                        result.add(convertClassLoaderURL(url));
                    }
                    else if (warDeployed) {
                        result.add(convertClassLoaderURL(url));
                    }
                    */
                    result.add(convertClassLoaderURL(url));
                }
            }
            return result.toArray(new Resource[result.size()]);
        }
    };
    resourceResolver.setPathMatcher(new AntPathMatcher() {

        @Override
        public boolean match(String pattern, String path) {
            if (path.endsWith(".class")) {
                String filename = GrailsStringUtils.getFileBasename(path);
                if (filename.contains("$"))
                    return false;
            }
            return super.match(pattern, path);
        }
    });
    scanner.setResourceLoader(resourceResolver);
    return scanner;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ResourceLoader(org.springframework.core.io.ResourceLoader) Resource(org.springframework.core.io.Resource) URL(java.net.URL) ClassPathBeanDefinitionScanner(org.springframework.context.annotation.ClassPathBeanDefinitionScanner) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) AntPathMatcher(org.springframework.util.AntPathMatcher)

Aggregations

ClassPathBeanDefinitionScanner (org.springframework.context.annotation.ClassPathBeanDefinitionScanner)10 Test (org.junit.jupiter.api.Test)3 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)2 ScopeMetadataResolver (org.springframework.context.annotation.ScopeMetadataResolver)2 GenericApplicationContext (org.springframework.context.support.GenericApplicationContext)2 GenericWebApplicationContext (org.springframework.web.context.support.GenericWebApplicationContext)2 GrailsPluginManager (grails.plugins.GrailsPluginManager)1 ServletContextEvent (jakarta.servlet.ServletContextEvent)1 IOException (java.io.IOException)1 URL (java.net.URL)1 LinkedHashSet (java.util.LinkedHashSet)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 BeanFactory (org.springframework.beans.factory.BeanFactory)1 HierarchicalBeanFactory (org.springframework.beans.factory.HierarchicalBeanFactory)1 AnnotatedBeanDefinition (org.springframework.beans.factory.annotation.AnnotatedBeanDefinition)1 BeanDefinitionRegistry (org.springframework.beans.factory.support.BeanDefinitionRegistry)1 BeanNameGenerator (org.springframework.beans.factory.support.BeanNameGenerator)1 AnnotatedBeanDefinitionReader (org.springframework.context.annotation.AnnotatedBeanDefinitionReader)1 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)1 ScopeMetadata (org.springframework.context.annotation.ScopeMetadata)1