Java Code Examples for org.springframework.context.annotation.ClassPathBeanDefinitionScanner#scan()

The following examples show how to use org.springframework.context.annotation.ClassPathBeanDefinitionScanner#scan() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BootShim.java    From spring-data-dev-tools with Apache License 2.0 6 votes vote down vote up
public BootShim(String[] args, ConfigurableApplicationContext context) {
	this.ctx = context;

	try {
		commandLine = SimpleShellCommandLineOptions.parseCommandLine(args);
	} catch (IOException var5) {
		throw new ShellException(var5.getMessage(), var5);
	}

	this.configureApplicationContext(this.ctx);
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner((BeanDefinitionRegistry) this.ctx);
	if (commandLine.getDisableInternalCommands()) {
		scanner.scan(new String[] { "org.springframework.shell.converters", "org.springframework.shell.plugin.support" });
	} else {
		scanner.scan(new String[] { "org.springframework.shell.commands", "org.springframework.shell.converters",
				"org.springframework.shell.plugin.support" });
	}

}
 
Example 2
Source File: GRpcApiRegister.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(GRpcServerScan.class.getCanonicalName()));
    if (annotationAttributes == null) {
        log.warn("GrpcScan was not found.Please check your configuration.");
        return;
    }
    ClassPathBeanDefinitionScanner classPathGrpcApiScanner = new ClassPathBeanDefinitionScanner(registry, false);
    classPathGrpcApiScanner.setResourceLoader(this.resourceLoader);
    classPathGrpcApiScanner.addIncludeFilter(new AnnotationTypeFilter(GRpcApi.class));
    List<String> basePackages = AutoConfigurationPackages.get(this.beanFactory);
    for (String pkg : annotationAttributes.getStringArray("basePackages")) {
        if (StringUtils.hasText(pkg)) {
            basePackages.add(pkg);
        }
    }
    classPathGrpcApiScanner.scan(StringUtils.toStringArray(basePackages));
}
 
Example 3
Source File: ClassPathBeanDefinitionScannerScopeIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private ApplicationContext createContext(ScopedProxyMode scopedProxyMode) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setBeanNameGenerator(new BeanNameGenerator() {
		@Override
		public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
			return 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;
}
 
Example 4
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private ApplicationContext createContext(final ScopedProxyMode scopedProxyMode) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setScopeMetadataResolver(new ScopeMetadataResolver() {
		@Override
		public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
			ScopeMetadata metadata = new ScopeMetadata();
			if (definition instanceof AnnotatedBeanDefinition) {
				AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
				for (String type : annDef.getMetadata().getAnnotationTypes()) {
					if (type.equals(javax.inject.Singleton.class.getName())) {
						metadata.setScopeName(BeanDefinition.SCOPE_SINGLETON);
						break;
					}
					else if (annDef.getMetadata().getMetaAnnotationTypes(type).contains(javax.inject.Scope.class.getName())) {
						metadata.setScopeName(type.substring(type.length() - 13, type.length() - 6).toLowerCase());
						metadata.setScopedProxyMode(scopedProxyMode);
						break;
					}
					else if (type.startsWith("javax.inject")) {
						metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
					}
				}
			}
			return metadata;
		}
	});

	// Scan twice in order to find errors in the bean definition compatibility check.
	scanner.scan(getClass().getPackage().getName());
	scanner.scan(getClass().getPackage().getName());

	context.registerAlias("classPathBeanDefinitionScannerJsr330ScopeIntegrationTests.SessionScopedTestBean", "session");
	context.refresh();
	return context;
}
 
Example 5
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private ApplicationContext createContext(final ScopedProxyMode scopedProxyMode) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setScopeMetadataResolver(new ScopeMetadataResolver() {
		@Override
		public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
			ScopeMetadata metadata = new ScopeMetadata();
			if (definition instanceof AnnotatedBeanDefinition) {
				AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
				for (String type : annDef.getMetadata().getAnnotationTypes()) {
					if (type.equals(javax.inject.Singleton.class.getName())) {
						metadata.setScopeName(BeanDefinition.SCOPE_SINGLETON);
						break;
					}
					else if (annDef.getMetadata().getMetaAnnotationTypes(type).contains(javax.inject.Scope.class.getName())) {
						metadata.setScopeName(type.substring(type.length() - 13, type.length() - 6).toLowerCase());
						metadata.setScopedProxyMode(scopedProxyMode);
						break;
					}
					else if (type.startsWith("javax.inject")) {
						metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
					}
				}
			}
			return metadata;
		}
	});

	// Scan twice in order to find errors in the bean definition compatibility check.
	scanner.scan(getClass().getPackage().getName());
	scanner.scan(getClass().getPackage().getName());

	context.registerAlias("classPathBeanDefinitionScannerJsr330ScopeIntegrationTests.SessionScopedTestBean", "session");
	context.refresh();
	return context;
}
 
Example 6
Source File: Spr8510Tests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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()));
}
 
Example 7
Source File: AnnotatedBeanDefinitionRegistryUtils.java    From spring-context-support with Apache License 2.0 5 votes vote down vote up
/**
 * Scan base packages for register {@link Component @Component}s
 *
 * @param registry     {@link BeanDefinitionRegistry}
 * @param basePackages base packages
 * @return the count of registered components.
 */
public static int scanBasePackages(BeanDefinitionRegistry registry, String... basePackages) {

    int count = 0;

    if (!ObjectUtils.isEmpty(basePackages)) {

        boolean debugEnabled = logger.isDebugEnabled();

        if (debugEnabled) {
            logger.debug(registry.getClass().getSimpleName() + " will scan base packages " + Arrays.asList(basePackages) + ".");
        }

        List<String> registeredBeanNames = Arrays.asList(registry.getBeanDefinitionNames());

        ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner = new ClassPathBeanDefinitionScanner(registry);
        count = classPathBeanDefinitionScanner.scan(basePackages);

        List<String> scannedBeanNames = new ArrayList<String>(count);
        scannedBeanNames.addAll(Arrays.asList(registry.getBeanDefinitionNames()));
        scannedBeanNames.removeAll(registeredBeanNames);

        if (debugEnabled) {
            logger.debug("The Scanned Components[ count : " + count + "] under base packages " + Arrays.asList(basePackages) + " : ");
        }

        for (String scannedBeanName : scannedBeanNames) {
            BeanDefinition scannedBeanDefinition = registry.getBeanDefinition(scannedBeanName);
            if (debugEnabled) {
                logger.debug("Component [ name : " + scannedBeanName + " , class : " + scannedBeanDefinition.getBeanClassName() + " ]");
            }
        }
    }

    return count;

}
 
Example 8
Source File: EnvironmentSystemIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void classPathBeanDefinitionScanner_inheritsEnvironmentFromEnvironmentCapableBDR_scanProfileAnnotatedComponents() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("org.springframework.core.env.scan2");
	ctx.refresh();
	assertThat(scanner.getEnvironment(), is((Environment)ctx.getEnvironment()));
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
Example 9
Source File: EnvironmentSystemIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void classPathBeanDefinitionScanner_inheritsEnvironmentFromEnvironmentCapableBDR_scanProfileAnnotatedComponents() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("org.springframework.core.env.scan2");
	ctx.refresh();
	assertThat(scanner.getEnvironment(), is((Environment)ctx.getEnvironment()));
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
Example 10
Source File: MSF4JSpringApplication.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * This will add a given service class to the running instance with given base path.
 *
 * @param configurableApplicationContext ConfigurableApplicationContext of running app
 * @param serviceClass                   Service class
 * @param basePath                       Base path to which the service get registered
 */
public SpringMicroservicesRunner addService(ConfigurableApplicationContext configurableApplicationContext,
                                            Class<?> serviceClass, String basePath) {
    ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner =
            new ClassPathBeanDefinitionScanner((BeanDefinitionRegistry) configurableApplicationContext);
    classPathBeanDefinitionScanner.scan(serviceClass.getPackage().getName());
    SpringMicroservicesRunner springMicroservicesRunner =
            configurableApplicationContext.getBean(SpringMicroservicesRunner.class);
    springMicroservicesRunner.deploy(basePath, configurableApplicationContext.getBean(serviceClass));
    return springMicroservicesRunner;
}
 
Example 11
Source File: Spr8510Tests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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()));
}
 
Example 12
Source File: EnodeBootstrapRegistrar.java    From enode with MIT License 5 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
    String declaringClass = metadata.getClass().getName();
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry, false, this.environment, this.resourceLoader);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Command.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(Event.class));
    AnnotationAttributes enodeScan = attributesFor(metadata, EnableEnode.class.getName());
    Set<String> basePackages = new LinkedHashSet<>();
    String[] basePackagesArray = enodeScan.getStringArray("basePackages");
    for (String pkg : basePackagesArray) {
        String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
                ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
        Collections.addAll(basePackages, tokenized);
    }
    for (Class<?> clazz : enodeScan.getClassArray("basePackageClasses")) {
        basePackages.add(ClassUtils.getPackageName(clazz));
    }
    if (basePackages.isEmpty()) {
        basePackages.add(ClassUtils.getPackageName(metadata.getClassName()));
    }
    scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
        @Override
        protected boolean matchClassName(String className) {
            return declaringClass.equals(className);
        }
    });
    String[] scanPackages = StringUtils.toStringArray(basePackages);
    ObjectContainer.BASE_PACKAGES = scanPackages;
    scanner.scan(scanPackages);
}
 
Example 13
Source File: EnvironmentSystemIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void classPathBeanDefinitionScanner_inheritsEnvironmentFromEnvironmentCapableBDR_scanProfileAnnotatedComponents() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("org.springframework.core.env.scan2");
	ctx.refresh();
	assertThat(scanner.getEnvironment(), is((Environment)ctx.getEnvironment()));
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
Example 14
Source File: EnvironmentSystemIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void classPathBeanDefinitionScanner_inheritsEnvironmentFromEnvironmentCapableBDR_scanProfileAnnotatedConfigClasses() {
	// it's actually ConfigurationClassPostProcessor's Environment that gets the job done here.
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
	scanner.scan("org.springframework.core.env.scan1");
	ctx.refresh();
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
Example 15
Source File: ClassPathBeanDefinitionScannerScopeIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
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;
}
 
Example 16
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private ApplicationContext createContext(final ScopedProxyMode scopedProxyMode) {
	GenericWebApplicationContext context = new GenericWebApplicationContext();
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setIncludeAnnotationConfig(false);
	scanner.setScopeMetadataResolver(new ScopeMetadataResolver() {
		@Override
		public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
			ScopeMetadata metadata = new ScopeMetadata();
			if (definition instanceof AnnotatedBeanDefinition) {
				AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
				for (String type : annDef.getMetadata().getAnnotationTypes()) {
					if (type.equals(javax.inject.Singleton.class.getName())) {
						metadata.setScopeName(BeanDefinition.SCOPE_SINGLETON);
						break;
					}
					else if (annDef.getMetadata().getMetaAnnotationTypes(type).contains(javax.inject.Scope.class.getName())) {
						metadata.setScopeName(type.substring(type.length() - 13, type.length() - 6).toLowerCase());
						metadata.setScopedProxyMode(scopedProxyMode);
						break;
					}
					else if (type.startsWith("javax.inject")) {
						metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
					}
				}
			}
			return metadata;
		}
	});

	// Scan twice in order to find errors in the bean definition compatibility check.
	scanner.scan(getClass().getPackage().getName());
	scanner.scan(getClass().getPackage().getName());

	context.registerAlias("classPathBeanDefinitionScannerJsr330ScopeIntegrationTests.SessionScopedTestBean", "session");
	context.refresh();
	return context;
}
 
Example 17
Source File: AnnotationConfigWebApplicationContext.java    From elasticactors with Apache License 2.0 4 votes vote down vote up
/**
 * 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 annotated 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.
 * @see #register(Class...)
 * @see #scan(String...)
 * @see #setConfigLocation(String)
 * @see #setConfigLocations(String[])
 * @see AnnotatedBeanDefinitionReader
 * @see ClassPathBeanDefinitionScanner
 */
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
    AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(beanFactory);
    reader.setEnvironment(this.getEnvironment());

    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(beanFactory);
    scanner.setEnvironment(this.getEnvironment());

    BeanNameGenerator beanNameGenerator = getBeanNameGenerator();
    ScopeMetadataResolver scopeMetadataResolver = getScopeMetadataResolver();
    if (beanNameGenerator != null) {
        reader.setBeanNameGenerator(beanNameGenerator);
        scanner.setBeanNameGenerator(beanNameGenerator);
        beanFactory.registerSingleton(
                AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
    }
    if (scopeMetadataResolver != null) {
        reader.setScopeMetadataResolver(scopeMetadataResolver);
        scanner.setScopeMetadataResolver(scopeMetadataResolver);
    }

    if (!this.annotatedClasses.isEmpty()) {
        if (logger.isInfoEnabled()) {
            logger.info("Registering annotated classes: [" +
                    StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) + "]");
        }
        reader.register(this.annotatedClasses.toArray(new Class<?>[0]));
    }

    if (!this.basePackages.isEmpty()) {
        if (logger.isInfoEnabled()) {
            logger.info("Scanning base packages: [" +
                    StringUtils.collectionToCommaDelimitedString(this.basePackages) + "]");
        }
        for (TypeFilter typeFilter : includeFilters) {
            scanner.addIncludeFilter(typeFilter);
        }
        scanner.scan(this.basePackages.toArray(new String[0]));
    }

    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
        for (String configLocation : configLocations) {
            try {
                Class<?> clazz = getClassLoader().loadClass(configLocation);
                if (logger.isInfoEnabled()) {
                    logger.info("Successfully resolved class for [" + configLocation + "]");
                }
                reader.register(clazz);
            }
            catch (ClassNotFoundException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Could not load class for config location [" + configLocation +
                            "] - trying package scan. " + ex);
                }
                int count = scanner.scan(configLocation);
                if (logger.isInfoEnabled()) {
                    if (count == 0) {
                        logger.info("No annotated classes found for specified class/package [" + configLocation + "]");
                    }
                    else {
                        logger.info("Found " + count + " annotated classes in package [" + configLocation + "]");
                    }
                }
            }
        }
    }
}
 
Example 18
Source File: AnnotationConfigWebApplicationContext.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * 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 annotated 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.annotatedClasses.isEmpty()) {
		if (logger.isDebugEnabled()) {
			logger.debug("Registering annotated classes: [" +
					StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) + "]");
		}
		reader.register(ClassUtils.toClassArray(this.annotatedClasses));
	}

	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 annotated classes found for specified class/package [" + configLocation + "]");
				}
			}
		}
	}
}
 
Example 19
Source File: AnnotationConfigWebApplicationContext.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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 annotated 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.annotatedClasses.isEmpty()) {
		if (logger.isInfoEnabled()) {
			logger.info("Registering annotated classes: [" +
					StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) + "]");
		}
		reader.register(this.annotatedClasses.toArray(new Class<?>[this.annotatedClasses.size()]));
	}

	if (!this.basePackages.isEmpty()) {
		if (logger.isInfoEnabled()) {
			logger.info("Scanning base packages: [" +
					StringUtils.collectionToCommaDelimitedString(this.basePackages) + "]");
		}
		scanner.scan(this.basePackages.toArray(new String[this.basePackages.size()]));
	}

	String[] configLocations = getConfigLocations();
	if (configLocations != null) {
		for (String configLocation : configLocations) {
			try {
				Class<?> clazz = getClassLoader().loadClass(configLocation);
				if (logger.isInfoEnabled()) {
					logger.info("Successfully resolved class for [" + configLocation + "]");
				}
				reader.register(clazz);
			}
			catch (ClassNotFoundException ex) {
				if (logger.isDebugEnabled()) {
					logger.debug("Could not load class for config location [" + configLocation +
							"] - trying package scan. " + ex);
				}
				int count = scanner.scan(configLocation);
				if (logger.isInfoEnabled()) {
					if (count == 0) {
						logger.info("No annotated classes found for specified class/package [" + configLocation + "]");
					}
					else {
						logger.info("Found " + count + " annotated classes in package [" + configLocation + "]");
					}
				}
			}
		}
	}
}
 
Example 20
Source File: AnnotationConfigWebApplicationContext.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * 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 annotated 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.annotatedClasses.isEmpty()) {
		if (logger.isInfoEnabled()) {
			logger.info("Registering annotated classes: [" +
					StringUtils.collectionToCommaDelimitedString(this.annotatedClasses) + "]");
		}
		reader.register(this.annotatedClasses.toArray(new Class<?>[this.annotatedClasses.size()]));
	}

	if (!this.basePackages.isEmpty()) {
		if (logger.isInfoEnabled()) {
			logger.info("Scanning base packages: [" +
					StringUtils.collectionToCommaDelimitedString(this.basePackages) + "]");
		}
		scanner.scan(this.basePackages.toArray(new String[this.basePackages.size()]));
	}

	String[] configLocations = getConfigLocations();
	if (configLocations != null) {
		for (String configLocation : configLocations) {
			try {
				Class<?> clazz = getClassLoader().loadClass(configLocation);
				if (logger.isInfoEnabled()) {
					logger.info("Successfully resolved class for [" + configLocation + "]");
				}
				reader.register(clazz);
			}
			catch (ClassNotFoundException ex) {
				if (logger.isDebugEnabled()) {
					logger.debug("Could not load class for config location [" + configLocation +
							"] - trying package scan. " + ex);
				}
				int count = scanner.scan(configLocation);
				if (logger.isInfoEnabled()) {
					if (count == 0) {
						logger.info("No annotated classes found for specified class/package [" + configLocation + "]");
					}
					else {
						logger.info("Found " + count + " annotated classes in package [" + configLocation + "]");
					}
				}
			}
		}
	}
}