Java Code Examples for org.springframework.context.annotation.AnnotatedBeanDefinitionReader#register()

The following examples show how to use org.springframework.context.annotation.AnnotatedBeanDefinitionReader#register() . 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: EnvironmentSecurityManagerIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void securityManagerDisallowsAccessToSystemEnvironmentButAllowsAccessToIndividualKeys() {
	SecurityManager securityManager = new SecurityManager() {
		@Override
		public void checkPermission(Permission perm) {
			// Disallowing access to System#getenv means that our
			// ReadOnlySystemAttributesMap will come into play.
			if ("getenv.*".equals(perm.getName())) {
				throw new AccessControlException("Accessing the system environment is disallowed");
			}
		}
	};
	System.setSecurityManager(securityManager);

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
	reader.register(C1.class);
	assertThat(bf.containsBean("c1"), is(true));
}
 
Example 2
Source File: AnnotatedBeanDefinitionParsingDemo.java    From geekbang-lessons with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    // 基于 Java 注解的 AnnotatedBeanDefinitionReader 的实现
    AnnotatedBeanDefinitionReader beanDefinitionReader = new AnnotatedBeanDefinitionReader(beanFactory);
    int beanDefinitionCountBefore = beanFactory.getBeanDefinitionCount();
    // 注册当前类(非 @Component class)
    beanDefinitionReader.register(AnnotatedBeanDefinitionParsingDemo.class);
    int beanDefinitionCountAfter = beanFactory.getBeanDefinitionCount();
    int beanDefinitionCount = beanDefinitionCountAfter - beanDefinitionCountBefore;
    System.out.println("已加载 BeanDefinition 数量:" + beanDefinitionCount);
    // 普通的 Class 作为 Component 注册到 Spring IoC 容器后,通常 Bean 名称为 annotatedBeanDefinitionParsingDemo
    // Bean 名称生成来自于 BeanNameGenerator,注解实现 AnnotationBeanNameGenerator
    AnnotatedBeanDefinitionParsingDemo demo = beanFactory.getBean("annotatedBeanDefinitionParsingDemo",
            AnnotatedBeanDefinitionParsingDemo.class);
    System.out.println(demo);
}
 
Example 3
Source File: EnvironmentSecurityManagerIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void securityManagerDisallowsAccessToSystemEnvironmentButAllowsAccessToIndividualKeys() {
	SecurityManager securityManager = new SecurityManager() {
		@Override
		public void checkPermission(Permission perm) {
			// Disallowing access to System#getenv means that our
			// ReadOnlySystemAttributesMap will come into play.
			if ("getenv.*".equals(perm.getName())) {
				throw new AccessControlException("Accessing the system environment is disallowed");
			}
		}
	};
	System.setSecurityManager(securityManager);

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
	reader.register(C1.class);
	assertThat(bf.containsBean("c1"), is(true));
}
 
Example 4
Source File: EnvironmentSecurityManagerIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void securityManagerDisallowsAccessToSystemEnvironmentButAllowsAccessToIndividualKeys() {
	SecurityManager securityManager = new SecurityManager() {
		@Override
		public void checkPermission(Permission perm) {
			// Disallowing access to System#getenv means that our
			// ReadOnlySystemAttributesMap will come into play.
			if ("getenv.*".equals(perm.getName())) {
				throw new AccessControlException("Accessing the system environment is disallowed");
			}
		}
	};
	System.setSecurityManager(securityManager);

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
	reader.register(C1.class);
	assertThat(bf.containsBean("c1"), is(true));
}
 
Example 5
Source File: EngineBeanDefinitionParser.java    From score with Apache License 2.0 6 votes vote down vote up
private void loadContexts(Element element, BeanDefinitionRegistry beanDefinitionRegistry) {
    String externalDatabase = element.getAttribute("externalDatabase");
    if (StringUtils.isBlank(externalDatabase) || externalDatabase.equals(Boolean.FALSE.toString())) {
        AnnotatedBeanDefinitionReader definitionReader = new AnnotatedBeanDefinitionReader(beanDefinitionRegistry);
        definitionReader.register(ScoreDefaultDatasourceContext.class);
        definitionReader.register(ScoreDatabaseContext.class);
    }

    String repositoriesContextPath = "META-INF/spring/score/context/scoreRepositoryContext.xml";

    String ignoreEngineJobs = element.getAttribute("ignoreEngineJobs");
    if(StringUtils.isNotBlank(ignoreEngineJobs) && ignoreEngineJobs.equals(Boolean.TRUE.toString())){
        new XmlBeanDefinitionReader(beanDefinitionRegistry).loadBeanDefinitions(repositoriesContextPath);
    }
    else{
        new XmlBeanDefinitionReader(beanDefinitionRegistry).loadBeanDefinitions(repositoriesContextPath,ENGINE_JOBS_CONTEXT_LOCATION);
    }
}
 
Example 6
Source File: EnvironmentSecurityManagerIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void securityManagerDisallowsAccessToSystemEnvironmentAndDisallowsAccessToIndividualKey() {
	SecurityManager securityManager = new SecurityManager() {
		@Override
		public void checkPermission(Permission perm) {
			// Disallowing access to System#getenv means that our
			// ReadOnlySystemAttributesMap will come into play.
			if ("getenv.*".equals(perm.getName())) {
				throw new AccessControlException("Accessing the system environment is disallowed");
			}
			// Disallowing access to the spring.profiles.active property means that
			// the BeanDefinitionReader won't be able to determine which profiles are
			// active. We should see an INFO-level message in the console about this
			// and as a result, any components marked with a non-default profile will
			// be ignored.
			if (("getenv." + AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME).equals(perm.getName())) {
				throw new AccessControlException(
						format("Accessing system environment variable [%s] is disallowed",
								AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME));
			}
		}
	};
	System.setSecurityManager(securityManager);

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
	reader.register(C1.class);
	assertThat(bf.containsBean("c1"), is(false));
}
 
Example 7
Source File: EnvironmentSecurityManagerIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void securityManagerDisallowsAccessToSystemEnvironmentAndDisallowsAccessToIndividualKey() {
	SecurityManager securityManager = new SecurityManager() {
		@Override
		public void checkPermission(Permission perm) {
			// Disallowing access to System#getenv means that our
			// ReadOnlySystemAttributesMap will come into play.
			if ("getenv.*".equals(perm.getName())) {
				throw new AccessControlException("Accessing the system environment is disallowed");
			}
			// Disallowing access to the spring.profiles.active property means that
			// the BeanDefinitionReader won't be able to determine which profiles are
			// active. We should see an INFO-level message in the console about this
			// and as a result, any components marked with a non-default profile will
			// be ignored.
			if (("getenv." + AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME).equals(perm.getName())) {
				throw new AccessControlException(
						format("Accessing system environment variable [%s] is disallowed",
								AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME));
			}
		}
	};
	System.setSecurityManager(securityManager);

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
	reader.register(C1.class);
	assertThat(bf.containsBean("c1"), is(false));
}
 
Example 8
Source File: AnnotatedBeanDefinitionRegistryUtils.java    From spring-context-support with Apache License 2.0 5 votes vote down vote up
/**
 * Register Beans if not present in {@link BeanDefinitionRegistry registry}
 *
 * @param registry         {@link BeanDefinitionRegistry}
 * @param annotatedClasses {@link Annotation annotation} class
 */
public static void registerBeans(BeanDefinitionRegistry registry, Class<?>... annotatedClasses) {

    if (ObjectUtils.isEmpty(annotatedClasses)) {
        return;
    }

    Set<Class<?>> classesToRegister = new LinkedHashSet<Class<?>>(asList(annotatedClasses));

    // Remove all annotated-classes that have been registered
    Iterator<Class<?>> iterator = classesToRegister.iterator();

    while (iterator.hasNext()) {
        Class<?> annotatedClass = iterator.next();
        if (isPresentBean(registry, annotatedClass)) {
            iterator.remove();
        }
    }

    AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(registry);

    if (logger.isDebugEnabled()) {
        logger.debug(registry.getClass().getSimpleName() + " will register annotated classes : " + asList(annotatedClasses) + " .");
    }

    reader.register(classesToRegister.toArray(EMPTY_CLASS_ARRAY));

}
 
Example 9
Source File: RefreshableAnnotationConfigApplicationContext.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
private AnnotatedBeanDefinitionReader configure(AnnotatedBeanDefinitionReader reader) {

		Set<Class<?>> componentClasses = this.componentClasses;

		if (!componentClasses.isEmpty()) {
			getLogger().debug("Registering component classes: {}", componentClasses);
			reader.register(ClassUtils.toClassArray(componentClasses));
		}

		return reader;
	}
 
Example 10
Source File: EnvironmentSecurityManagerIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void securityManagerDisallowsAccessToSystemEnvironmentAndDisallowsAccessToIndividualKey() {
	SecurityManager securityManager = new SecurityManager() {
		@Override
		public void checkPermission(Permission perm) {
			// Disallowing access to System#getenv means that our
			// ReadOnlySystemAttributesMap will come into play.
			if ("getenv.*".equals(perm.getName())) {
				throw new AccessControlException("Accessing the system environment is disallowed");
			}
			// Disallowing access to the spring.profiles.active property means that
			// the BeanDefinitionReader won't be able to determine which profiles are
			// active. We should see an INFO-level message in the console about this
			// and as a result, any components marked with a non-default profile will
			// be ignored.
			if (("getenv." + AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME).equals(perm.getName())) {
				throw new AccessControlException(
						format("Accessing system environment variable [%s] is disallowed",
								AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME));
			}
		}
	};
	System.setSecurityManager(securityManager);

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf);
	reader.register(C1.class);
	assertThat(bf.containsBean("c1"), is(false));
}
 
Example 11
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 12
Source File: AnnotationConfigWebApplicationContext.java    From java-technology-stack 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 13
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 14
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 + "]");
					}
				}
			}
		}
	}
}
 
Example 15
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 + "]");
                    }
                }
            }
        }
    }
}