类org.springframework.context.annotation.AnnotatedBeanDefinitionReader源码实例Demo

下面列出了怎么用org.springframework.context.annotation.AnnotatedBeanDefinitionReader的API类实例代码及写法,或者点击链接到github查看源代码。

@Test
public void cronTaskWithScopedProxy() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	new AnnotatedBeanDefinitionReader(context).register(ProxiedCronTestBean.class, ProxiedCronTestBeanDependent.class);
	context.refresh();

	ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
	assertEquals(1, postProcessor.getScheduledTasks().size());

	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<CronTask> cronTasks = (List<CronTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
	assertEquals(1, cronTasks.size());
	CronTask task = cronTasks.get(0);
	ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
	Object targetObject = runnable.getTarget();
	Method targetMethod = runnable.getMethod();
	assertEquals(context.getBean(ScopedProxyUtils.getTargetBeanName("target")), targetObject);
	assertEquals("cron", targetMethod.getName());
	assertEquals("*/7 * * * * ?", task.getExpression());
}
 
源代码2 项目: spring-analysis-note   文件: SpringAtInjectTck.java
public static Test suite() {
	GenericApplicationContext ac = new GenericApplicationContext();
	AnnotatedBeanDefinitionReader bdr = new AnnotatedBeanDefinitionReader(ac);
	bdr.setScopeMetadataResolver(new Jsr330ScopeMetadataResolver());

	bdr.registerBean(Convertible.class);
	bdr.registerBean(DriversSeat.class, Drivers.class);
	bdr.registerBean(Seat.class, Primary.class);
	bdr.registerBean(V8Engine.class);
	bdr.registerBean(SpareTire.class, "spare");
	bdr.registerBean(Cupholder.class);
	bdr.registerBean(Tire.class, Primary.class);
	bdr.registerBean(FuelTank.class);

	ac.refresh();
	Car car = ac.getBean(Car.class);

	return Tck.testsFor(car, false, true);
}
 
@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));
}
 
@Before
public void setUp() {
	ServletContext servletContext = new MockServletContext();
	MockHttpServletRequest mockRequest = new MockHttpServletRequest(servletContext);
	mockRequest.setAttribute(FROM_CUSTOM_MOCK, FROM_CUSTOM_MOCK);
	RequestContextHolder.setRequestAttributes(new ServletWebRequest(mockRequest, new MockHttpServletResponse()));

	this.wac.setServletContext(servletContext);
	new AnnotatedBeanDefinitionReader(this.wac).register(WebConfig.class);
	this.wac.refresh();

	this.mockMvc = webAppContextSetup(this.wac)
			.defaultRequest(get("/").requestAttr(FROM_MVC_TEST_DEFAULT, FROM_MVC_TEST_DEFAULT))
			.alwaysExpect(status().isOk())
			.build();
}
 
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);
}
 
@Test
public void cronTaskWithScopedProxy() {
	BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
	context.registerBeanDefinition("postProcessor", processorDefinition);
	new AnnotatedBeanDefinitionReader(context).register(ProxiedCronTestBean.class, ProxiedCronTestBeanDependent.class);
	context.refresh();

	ScheduledTaskHolder postProcessor = context.getBean("postProcessor", ScheduledTaskHolder.class);
	assertEquals(1, postProcessor.getScheduledTasks().size());

	ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar)
			new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
	@SuppressWarnings("unchecked")
	List<CronTask> cronTasks = (List<CronTask>)
			new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
	assertEquals(1, cronTasks.size());
	CronTask task = cronTasks.get(0);
	ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
	Object targetObject = runnable.getTarget();
	Method targetMethod = runnable.getMethod();
	assertEquals(context.getBean(ScopedProxyUtils.getTargetBeanName("target")), targetObject);
	assertEquals("cron", targetMethod.getName());
	assertEquals("*/7 * * * * ?", task.getExpression());
}
 
源代码7 项目: java-technology-stack   文件: SpringAtInjectTck.java
public static Test suite() {
	GenericApplicationContext ac = new GenericApplicationContext();
	AnnotatedBeanDefinitionReader bdr = new AnnotatedBeanDefinitionReader(ac);
	bdr.setScopeMetadataResolver(new Jsr330ScopeMetadataResolver());

	bdr.registerBean(Convertible.class);
	bdr.registerBean(DriversSeat.class, Drivers.class);
	bdr.registerBean(Seat.class, Primary.class);
	bdr.registerBean(V8Engine.class);
	bdr.registerBean(SpareTire.class, "spare");
	bdr.registerBean(Cupholder.class);
	bdr.registerBean(Tire.class, Primary.class);
	bdr.registerBean(FuelTank.class);

	ac.refresh();
	Car car = ac.getBean(Car.class);

	return Tck.testsFor(car, false, true);
}
 
@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));
}
 
@Before
public void setUp() {
	ServletContext servletContext = new MockServletContext();
	MockHttpServletRequest mockRequest = new MockHttpServletRequest(servletContext);
	mockRequest.setAttribute(FROM_CUSTOM_MOCK, FROM_CUSTOM_MOCK);
	RequestContextHolder.setRequestAttributes(new ServletWebRequest(mockRequest, new MockHttpServletResponse()));

	this.wac.setServletContext(servletContext);
	new AnnotatedBeanDefinitionReader(this.wac).register(WebConfig.class);
	this.wac.refresh();

	this.mockMvc = webAppContextSetup(this.wac)
			.defaultRequest(get("/").requestAttr(FROM_MVC_TEST_DEFAULT, FROM_MVC_TEST_DEFAULT))
			.alwaysExpect(status().isOk())
			.build();
}
 
源代码10 项目: spring4-understanding   文件: SpringAtInjectTck.java
public static Test suite() {
	GenericApplicationContext ac = new GenericApplicationContext();
	AnnotatedBeanDefinitionReader bdr = new AnnotatedBeanDefinitionReader(ac);
	bdr.setScopeMetadataResolver(new Jsr330ScopeMetadataResolver());

	bdr.registerBean(Convertible.class);
	bdr.registerBean(DriversSeat.class, Drivers.class);
	bdr.registerBean(Seat.class, Primary.class);
	bdr.registerBean(V8Engine.class);
	bdr.registerBean(SpareTire.class, "spare");
	bdr.registerBean(Cupholder.class);
	bdr.registerBean(Tire.class, Primary.class);
	bdr.registerBean(FuelTank.class);

	ac.refresh();
	Car car = ac.getBean(Car.class);

	return Tck.testsFor(car, false, true);
}
 
@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));
}
 
@Before
public void setUp() {
	ServletContext servletContext = new MockServletContext();
	MockHttpServletRequest mockRequest = new MockHttpServletRequest(servletContext);
	mockRequest.setAttribute(FROM_CUSTOM_MOCK, FROM_CUSTOM_MOCK);
	RequestContextHolder.setRequestAttributes(new ServletWebRequest(mockRequest, new MockHttpServletResponse()));

	this.wac.setServletContext(servletContext);
	new AnnotatedBeanDefinitionReader(this.wac).register(WebConfig.class);
	this.wac.refresh();

	this.mockMvc = webAppContextSetup(this.wac)
			.defaultRequest(get("/").requestAttr(FROM_MVC_TEST_DEFAULT, FROM_MVC_TEST_DEFAULT))
			.alwaysExpect(status().isOk())
			.build();
}
 
源代码13 项目: score   文件: EngineBeanDefinitionParser.java
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);
    }
}
 
@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));
}
 
@Test
public void annotatedBeanDefinitionReader_inheritsEnvironmentFromEnvironmentCapableBDR() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	new AnnotatedBeanDefinitionReader(ctx).register(Config.class);
	ctx.refresh();
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
/**
 * Register classes in the supplied {@linkplain GenericWebApplicationContext context}
 * from the classes in the supplied {@link WebMergedContextConfiguration}.
 * <p>Each class must represent an <em>annotated class</em>. An
 * {@link AnnotatedBeanDefinitionReader} is used to register the appropriate
 * bean definitions.
 * @param context the context in which the annotated classes should be registered
 * @param webMergedConfig the merged configuration from which the classes should be retrieved
 * @see AbstractGenericWebContextLoader#loadBeanDefinitions
 */
@Override
protected void loadBeanDefinitions(
		GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) {

	Class<?>[] annotatedClasses = webMergedConfig.getClasses();
	if (logger.isDebugEnabled()) {
		logger.debug("Registering annotated classes: " + ObjectUtils.nullSafeToString(annotatedClasses));
	}
	new AnnotatedBeanDefinitionReader(context).register(annotatedClasses);
}
 
@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));
}
 
@Test
public void annotatedBeanDefinitionReader_inheritsEnvironmentFromEnvironmentCapableBDR() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	new AnnotatedBeanDefinitionReader(ctx).register(Config.class);
	ctx.refresh();
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
/**
 * Register classes in the supplied {@linkplain GenericWebApplicationContext context}
 * from the classes in the supplied {@link WebMergedContextConfiguration}.
 * <p>Each class must represent an <em>annotated class</em>. An
 * {@link AnnotatedBeanDefinitionReader} is used to register the appropriate
 * bean definitions.
 * @param context the context in which the annotated classes should be registered
 * @param webMergedConfig the merged configuration from which the classes should be retrieved
 * @see AbstractGenericWebContextLoader#loadBeanDefinitions
 */
@Override
protected void loadBeanDefinitions(
		GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) {

	Class<?>[] annotatedClasses = webMergedConfig.getClasses();
	if (logger.isDebugEnabled()) {
		logger.debug("Registering annotated classes: " + ObjectUtils.nullSafeToString(annotatedClasses));
	}
	new AnnotatedBeanDefinitionReader(context).register(annotatedClasses);
}
 
/**
 * 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));

}
 
/**
 * Loads {@link BeanDefinition BeanDefinitions} from Annotation configuration (component) classes
 * as well as from other resource locations (e.g. XML).
 *
 * @param beanFactory {@link DefaultListableBeanFactory} to configure.
 * @throws BeansException if loading and configuring the {@link BeanDefinition BeanDefintions} for the target
 * {@link DefaultListableBeanFactory} fails.
 * @see org.springframework.beans.factory.support.DefaultListableBeanFactory
 * @see #newAnnotatedBeanDefinitionReader(BeanDefinitionRegistry)
 * @see #newClassBeanDefinitionScanner(BeanDefinitionRegistry)
 * @see #getConfigLocations()
 */
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException {

	AnnotatedBeanDefinitionReader reader = configure(newAnnotatedBeanDefinitionReader(beanFactory));

	ClassPathBeanDefinitionScanner scanner = configure(newClassBeanDefinitionScanner(beanFactory));

	getBeanNameGenerator().ifPresent(beanNameGenerator -> {
		reader.setBeanNameGenerator(beanNameGenerator);
		scanner.setBeanNameGenerator(beanNameGenerator);
		beanFactory.registerSingleton(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);
	});

	getScopeMetadataResolver().ifPresent(scopeMetadataResolver -> {
		reader.setScopeMetadataResolver(scopeMetadataResolver);
		scanner.setScopeMetadataResolver(scopeMetadataResolver);
	});

	Arrays.stream(ArrayUtils.nullSafeArray(getConfigLocations(), String.class)).forEach(configLocation -> {
		try {
			Class<?> type = ClassUtils.forName(configLocation, getClassLoader());
			getLogger().trace("Registering [{}]", configLocation);
			reader.register(type);
		}
		catch (ClassNotFoundException cause) {

			getLogger().trace(String.format("Could not load class for config location [%s] - trying package scan.",
				configLocation), cause);

			if (scanner.scan(configLocation) == 0) {
				getLogger().debug("No component classes found for specified class/package [{}]", configLocation);
			}
		}
	});
}
 
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;
	}
 
@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));
}
 
@Test
public void annotatedBeanDefinitionReader_inheritsEnvironmentFromEnvironmentCapableBDR() {
	GenericApplicationContext ctx = new GenericApplicationContext();
	ctx.setEnvironment(prodEnv);
	new AnnotatedBeanDefinitionReader(ctx).register(Config.class);
	ctx.refresh();
	assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false));
	assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true));
}
 
源代码25 项目: Mycat-openEP   文件: SpringInitializer.java
private static void initAnnotatedConf(GenericApplicationContext context){
	Class componentScanAnnotated=ProcessInfo.getAnnotationInitClass();
	if(componentScanAnnotated!=null){
		AnnotatedGenericBeanDefinition def=new AnnotatedGenericBeanDefinition(ProcessInfo.getAnnotationInitClass());
		AnnotatedBeanDefinitionReader reader=new AnnotatedBeanDefinitionReader(context);
		AnnotationScopeMetadataResolver resolver=new AnnotationScopeMetadataResolver();
		resolver.resolveScopeMetadata(def);
		reader.setScopeMetadataResolver(resolver);
	}
}
 
/**
 * 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 + "]");
				}
			}
		}
	}
}
 
源代码27 项目: spring-analysis-note   文件: HybridContextLoader.java
@Override
protected void loadBeanDefinitions(GenericApplicationContext context, MergedContextConfiguration mergedConfig) {
	// Order doesn't matter: <bean> always wins over @Bean.
	new XmlBeanDefinitionReader(context).loadBeanDefinitions(mergedConfig.getLocations());
	new AnnotatedBeanDefinitionReader(context).register(mergedConfig.getClasses());
}
 
@Override
public void initialize(GenericApplicationContext applicationContext) {
	new AnnotatedBeanDefinitionReader(applicationContext).register(FooConfig.class);
}
 
@Override
public void initialize(GenericApplicationContext applicationContext) {
	new AnnotatedBeanDefinitionReader(applicationContext).register(GlobalConfig.class);
}
 
/**
 * 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 + "]");
				}
			}
		}
	}
}
 
 同包方法