org.springframework.beans.factory.BeanDefinitionStoreException Java Examples

The following examples show how to use org.springframework.beans.factory.BeanDefinitionStoreException. 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: PropertiesBeanDefinitionReader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Load bean definitions from the specified properties file.
 * @param encodedResource the resource descriptor for the properties file,
 * allowing to specify an encoding to use for parsing the file
 * @param prefix a filter within the keys in the map: e.g. 'beans.'
 * (can be empty or {@code null})
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 */
public int loadBeanDefinitions(EncodedResource encodedResource, String prefix)
		throws BeanDefinitionStoreException {

	Properties props = new Properties();
	try {
		InputStream is = encodedResource.getResource().getInputStream();
		try {
			if (encodedResource.getEncoding() != null) {
				getPropertiesPersister().load(props, new InputStreamReader(is, encodedResource.getEncoding()));
			}
			else {
				getPropertiesPersister().load(props, is);
			}
		}
		finally {
			is.close();
		}
		return registerBeanDefinitions(props, prefix, encodedResource.getResource().getDescription());
	}
	catch (IOException ex) {
		throw new BeanDefinitionStoreException("Could not parse properties from " + encodedResource.getResource(), ex);
	}
}
 
Example #2
Source File: PlaceholderConfigurerSupport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
		StringValueResolver valueResolver) {

	BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver);

	String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames();
	for (String curName : beanNames) {
		// Check that we're not parsing our own bean definition,
		// to avoid failing on unresolvable placeholders in properties file locations.
		if (!(curName.equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) {
			BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(curName);
			try {
				visitor.visitBeanDefinition(bd);
			}
			catch (Exception ex) {
				throw new BeanDefinitionStoreException(bd.getResourceDescription(), curName, ex.getMessage(), ex);
			}
		}
	}

	// New in Spring 2.5: resolve placeholders in alias target names and aliases as well.
	beanFactoryToProcess.resolveAliases(valueResolver);

	// New in Spring 3.0: resolve placeholders in embedded values such as annotation attributes.
	beanFactoryToProcess.addEmbeddedValueResolver(valueResolver);
}
 
Example #3
Source File: DefaultBeanDefinitionDocumentReader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Process the given bean element, parsing the bean definition
 * and registering it with the registry.
 */
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
	BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
	if (bdHolder != null) {
		bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
		try {
			// Register the final decorated instance.
			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
		}
		catch (BeanDefinitionStoreException ex) {
			getReaderContext().error("Failed to register bean definition with name '" +
					bdHolder.getBeanName() + "'", ele, ex);
		}
		// Send registration event.
		getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
	}
}
 
Example #4
Source File: ViewResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testXmlViewResolverDefaultLocation() {
	StaticWebApplicationContext wac = new StaticWebApplicationContext() {
		@Override
		protected Resource getResourceByPath(String path) {
			assertTrue("Correct default location", XmlViewResolver.DEFAULT_LOCATION.equals(path));
			return super.getResourceByPath(path);
		}
	};
	wac.setServletContext(new MockServletContext());
	wac.refresh();
	XmlViewResolver vr = new XmlViewResolver();
	try {
		vr.setApplicationContext(wac);
		vr.afterPropertiesSet();
		fail("Should have thrown BeanDefinitionStoreException");
	}
	catch (BeanDefinitionStoreException ex) {
		// expected
	}
}
 
Example #5
Source File: DefaultBeanDefinitionDocumentReader.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Process the given bean element, parsing the bean definition
 * and registering it with the registry.
 */
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
	// 注释 1.15 解析 bean 名称的元素
	BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
	if (bdHolder != null) {
		bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
		try {
			// Register the final decorated instance. (注释 1.16 注册最后修饰后的实例)
			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
		}
		catch (BeanDefinitionStoreException ex) {
			getReaderContext().error("Failed to register bean definition with name '" +
					bdHolder.getBeanName() + "'", ele, ex);
		}
		// Send registration event. 通知相关的监听器,表示这个 bean 已经加载完成
		getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
	}
}
 
Example #6
Source File: PropertyResourceConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testPropertyPlaceholderConfigurerWithUnresolvableSystemProperty() {
	factory.registerBeanDefinition("tb", genericBeanDefinition(TestBean.class)
			.addPropertyValue("touchy", "${user.dir}").getBeanDefinition());

	PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
	ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_NEVER);

	try {
		ppc.postProcessBeanFactory(factory);
		fail("Should have thrown BeanDefinitionStoreException");
	}
	catch (BeanDefinitionStoreException ex) {
		// expected
		assertTrue(ex.getMessage().contains("user.dir"));
	}
}
 
Example #7
Source File: PropertyResourceConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testPropertyPlaceholderConfigurerWithUnresolvablePlaceholder() {
	factory.registerBeanDefinition("tb", genericBeanDefinition(TestBean.class)
			.addPropertyValue("name", "${ref}").getBeanDefinition());

	PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();

	try {
		ppc.postProcessBeanFactory(factory);
		fail("Should have thrown BeanDefinitionStoreException");
	}
	catch (BeanDefinitionStoreException ex) {
		// expected
		assertTrue(ex.getMessage().contains("ref"));
	}
}
 
Example #8
Source File: BeanDefinitionReaderUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Register the given bean definition with the given bean factory.
 * @param definitionHolder the bean definition including name and aliases
 * @param registry the bean factory to register with
 * @throws BeanDefinitionStoreException if registration failed
 */
public static void registerBeanDefinition(
		BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
		throws BeanDefinitionStoreException {

	// Register bean definition under primary name.
	// 注释 1.17 在 DefaultListableBeanFactory 的 beanDefinitionMap 中添加 bean 定义
	String beanName = definitionHolder.getBeanName();
	registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

	// Register aliases for bean name, if any.
	String[] aliases = definitionHolder.getAliases();
	if (aliases != null) {
		for (String alias : aliases) {
			registry.registerAlias(beanName, alias);
		}
	}
}
 
Example #9
Source File: PropertyResourceConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testPropertyPlaceholderConfigurerWithCircularReference() {
	factory.registerBeanDefinition("tb", genericBeanDefinition(TestBean.class)
			.addPropertyValue("age", "${age}")
			.addPropertyValue("name", "name${var}")
			.getBeanDefinition());

	PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
	Properties props = new Properties();
	props.setProperty("age", "99");
	props.setProperty("var", "${m}");
	props.setProperty("m", "${var}");
	ppc.setProperties(props);

	try {
		ppc.postProcessBeanFactory(factory);
		fail("Should have thrown BeanDefinitionStoreException");
	}
	catch (BeanDefinitionStoreException ex) {
		// expected
	}
}
 
Example #10
Source File: ScriptFactoryPostProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected boolean resolveProxyTargetClass(BeanDefinition beanDefinition) {
	boolean proxyTargetClass = this.defaultProxyTargetClass;
	Object attributeValue = beanDefinition.getAttribute(PROXY_TARGET_CLASS_ATTRIBUTE);
	if (attributeValue instanceof Boolean) {
		proxyTargetClass = (Boolean) attributeValue;
	}
	else if (attributeValue instanceof String) {
		proxyTargetClass = Boolean.valueOf((String) attributeValue);
	}
	else if (attributeValue != null) {
		throw new BeanDefinitionStoreException("Invalid proxy target class attribute [" +
				PROXY_TARGET_CLASS_ATTRIBUTE + "] with value '" + attributeValue +
				"': needs to be of type Boolean or String");
	}
	return proxyTargetClass;
}
 
Example #11
Source File: PropertyResourceConfigurerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testPropertyPlaceholderConfigurerWithCircularReference() {
	factory.registerBeanDefinition("tb", genericBeanDefinition(TestBean.class)
			.addPropertyValue("age", "${age}")
			.addPropertyValue("name", "name${var}")
			.getBeanDefinition());

	PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
	Properties props = new Properties();
	props.setProperty("age", "99");
	props.setProperty("var", "${m}");
	props.setProperty("m", "${var}");
	ppc.setProperties(props);

	try {
		ppc.postProcessBeanFactory(factory);
		fail("Should have thrown BeanDefinitionStoreException");
	}
	catch (BeanDefinitionStoreException ex) {
		// expected
	}
}
 
Example #12
Source File: BeanDefinitionReaderUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Register the given bean definition with the given bean factory.
 * @param definitionHolder the bean definition including name and aliases
 * @param registry the bean factory to register with
 * @throws BeanDefinitionStoreException if registration failed
 */
public static void registerBeanDefinition(
		BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
		throws BeanDefinitionStoreException {

	// Register bean definition under primary name.
	String beanName = definitionHolder.getBeanName();
	registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

	// Register aliases for bean name, if any.
	String[] aliases = definitionHolder.getAliases();
	if (aliases != null) {
		for (String alias : aliases) {
			registry.registerAlias(beanName, alias);
		}
	}
}
 
Example #13
Source File: PreferencesPlaceholderConfigurer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Resolve the given path and key against the given Preferences.
 * @param path the preferences path (placeholder part before '/')
 * @param key the preferences key (placeholder part after '/')
 * @param preferences the Preferences to resolve against
 * @return the value for the placeholder, or {@code null} if none found
 */
protected String resolvePlaceholder(String path, String key, Preferences preferences) {
	if (path != null) {
		 // Do not create the node if it does not exist...
		try {
			if (preferences.nodeExists(path)) {
				return preferences.node(path).get(key, null);
			}
			else {
				return null;
			}
		}
		catch (BackingStoreException ex) {
			throw new BeanDefinitionStoreException("Cannot access specified node path [" + path + "]", ex);
		}
	}
	else {
		return preferences.get(key, null);
	}
}
 
Example #14
Source File: PlaceholderConfigurerSupport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
		StringValueResolver valueResolver) {

	BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver);

	String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames();
	for (String curName : beanNames) {
		// Check that we're not parsing our own bean definition,
		// to avoid failing on unresolvable placeholders in properties file locations.
		if (!(curName.equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) {
			BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(curName);
			try {
				visitor.visitBeanDefinition(bd);
			}
			catch (Exception ex) {
				throw new BeanDefinitionStoreException(bd.getResourceDescription(), curName, ex.getMessage(), ex);
			}
		}
	}

	// New in Spring 2.5: resolve placeholders in alias target names and aliases as well.
	beanFactoryToProcess.resolveAliases(valueResolver);

	// New in Spring 3.0: resolve placeholders in embedded values such as annotation attributes.
	beanFactoryToProcess.addEmbeddedValueResolver(valueResolver);
}
 
Example #15
Source File: ScriptFactoryPostProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Get the refresh check delay for the given {@link ScriptFactory} {@link BeanDefinition}.
 * If the {@link BeanDefinition} has a
 * {@link org.springframework.core.AttributeAccessor metadata attribute}
 * under the key {@link #REFRESH_CHECK_DELAY_ATTRIBUTE} which is a valid {@link Number}
 * type, then this value is used. Otherwise, the {@link #defaultRefreshCheckDelay}
 * value is used.
 * @param beanDefinition the BeanDefinition to check
 * @return the refresh check delay
 */
protected long resolveRefreshCheckDelay(BeanDefinition beanDefinition) {
	long refreshCheckDelay = this.defaultRefreshCheckDelay;
	Object attributeValue = beanDefinition.getAttribute(REFRESH_CHECK_DELAY_ATTRIBUTE);
	if (attributeValue instanceof Number) {
		refreshCheckDelay = ((Number) attributeValue).longValue();
	}
	else if (attributeValue instanceof String) {
		refreshCheckDelay = Long.parseLong((String) attributeValue);
	}
	else if (attributeValue != null) {
		throw new BeanDefinitionStoreException("Invalid refresh check delay attribute [" +
				REFRESH_CHECK_DELAY_ATTRIBUTE + "] with value '" + attributeValue +
				"': needs to be of type Number or String");
	}
	return refreshCheckDelay;
}
 
Example #16
Source File: ContextLoaderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testContextLoaderWithDefaultLocation() throws Exception {
	MockServletContext sc = new MockServletContext("");
	ServletContextListener listener = new ContextLoaderListener();
	ServletContextEvent event = new ServletContextEvent(sc);
	try {
		listener.contextInitialized(event);
		fail("Should have thrown BeanDefinitionStoreException");
	}
	catch (BeanDefinitionStoreException ex) {
		// expected
		assertTrue(ex.getCause() instanceof IOException);
		assertTrue(ex.getCause().getMessage().contains("/WEB-INF/applicationContext.xml"));
	}
}
 
Example #17
Source File: CacheAdviceParserTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void keyAndKeyGeneratorCannotBeSetTogether() {
	try {
		new GenericXmlApplicationContext("/org/springframework/cache/config/cache-advice-invalid.xml");
		fail("Should have failed to load context, one advise define both a key and a key generator");
	}
	catch (BeanDefinitionStoreException ex) {
		// TODO better exception handling
	}
}
 
Example #18
Source File: BroadcastServiceManager.java    From Alice-LiveMan with GNU Affero General Public License v3.0 5 votes vote down vote up
public BroadcastService getBroadcastService(String accountSite) {
    for (BroadcastService broadcastService : broadcastServiceMap.values()) {
        if (broadcastService.isMatch(accountSite)) {
            return broadcastService;
        }
    }
    throw new BeanDefinitionStoreException("没有找到可以推流到[" + accountSite + "]的BroadcastService");
}
 
Example #19
Source File: ReloadingPropertyPlaceholderConfigurer.java    From disconf with Apache License 2.0 5 votes vote down vote up
/**
 * copy & paste, just so we can insert our own visitor.
 * 启动时 进行配置的解析
 */
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
        throws BeansException {

    BeanDefinitionVisitor visitor =
            new ReloadingPropertyPlaceholderConfigurer.PlaceholderResolvingBeanDefinitionVisitor(props);
    String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames();
    for (int i = 0; i < beanNames.length; i++) {
        // Check that we're not parsing our own bean definition,
        // to avoid failing on unresolvable placeholders in net.unicon.iamlabs.spring.properties.example.net
        // .unicon.iamlabs.spring.properties file locations.
        if (!(beanNames[i].equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) {
            this.currentBeanName = beanNames[i];
            try {
                BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(beanNames[i]);
                try {
                    visitor.visitBeanDefinition(bd);
                } catch (BeanDefinitionStoreException ex) {
                    throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanNames[i],
                            ex.getMessage());
                }
            } finally {
                currentBeanName = null;
            }
        }
    }

    StringValueResolver stringValueResolver = new PlaceholderResolvingStringValueResolver(props);

    // New in Spring 2.5: resolve placeholders in alias target names and aliases as well.
    beanFactoryToProcess.resolveAliases(stringValueResolver);

    // New in Spring 3.0: resolve placeholders in embedded values such as annotation attributes.
    beanFactoryToProcess.addEmbeddedValueResolver(stringValueResolver);
}
 
Example #20
Source File: InvalidBindingConfigurationTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testDuplicateBeanByBindingConfig() {
	assertThatThrownBy(() -> SpringApplication.run(TestBindingConfig.class))
			.isInstanceOf(BeanDefinitionStoreException.class)
			.hasMessageContaining("bean definition with this name already exists")
			.hasMessageContaining(TestInvalidBinding.NAME).hasNoCause();
}
 
Example #21
Source File: EnableAsyncTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Fails with classpath errors on trying to classload AnnotationAsyncExecutionAspect.
 */
@Test(expected = BeanDefinitionStoreException.class)
public void aspectModeAspectJAttemptsToRegisterAsyncAspect() {
	@SuppressWarnings("resource")
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(AspectJAsyncAnnotationConfig.class);
	ctx.refresh();
}
 
Example #22
Source File: XmlBeanDefinitionReader.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Load bean definitions from the specified XML file.
 * @param encodedResource the resource descriptor for the XML file,
 * allowing to specify an encoding to use for parsing the file
 * @return the number of bean definitions found
 * @throws BeanDefinitionStoreException in case of loading or parsing errors
 */
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
	Assert.notNull(encodedResource, "EncodedResource must not be null");
	if (logger.isTraceEnabled()) {
		logger.trace("Loading XML bean definitions from " + encodedResource);
	}

	Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
	if (currentResources == null) {
		currentResources = new HashSet<>(4);
		this.resourcesCurrentlyBeingLoaded.set(currentResources);
	}
	if (!currentResources.add(encodedResource)) {
		throw new BeanDefinitionStoreException(
				"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
	}
	try {
		InputStream inputStream = encodedResource.getResource().getInputStream();
		try {
			InputSource inputSource = new InputSource(inputStream);
			if (encodedResource.getEncoding() != null) {
				inputSource.setEncoding(encodedResource.getEncoding());
			}
			return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
		}
		finally {
			inputStream.close();
		}
	}
	catch (IOException ex) {
		throw new BeanDefinitionStoreException(
				"IOException parsing XML document from " + encodedResource.getResource(), ex);
	}
	finally {
		currentResources.remove(encodedResource);
		if (currentResources.isEmpty()) {
			this.resourcesCurrentlyBeingLoaded.remove();
		}
	}
}
 
Example #23
Source File: BeanDefinitionReaderUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generate a bean name for the given bean definition, unique within the
 * given bean factory.
 * @param definition the bean definition to generate a bean name for
 * @param registry the bean factory that the definition is going to be
 * registered with (to check for existing bean names)
 * @param isInnerBean whether the given bean definition will be registered
 * as inner bean or as top-level bean (allowing for special name generation
 * for inner beans versus top-level beans)
 * @return the generated bean name
 * @throws BeanDefinitionStoreException if no unique name can be generated
 * for the given bean definition
 */
public static String generateBeanName(
		BeanDefinition definition, BeanDefinitionRegistry registry, boolean isInnerBean)
		throws BeanDefinitionStoreException {

	String generatedBeanName = definition.getBeanClassName();
	if (generatedBeanName == null) {
		if (definition.getParentName() != null) {
			generatedBeanName = definition.getParentName() + "$child";
		}
		else if (definition.getFactoryBeanName() != null) {
			generatedBeanName = definition.getFactoryBeanName() + "$created";
		}
	}
	if (!StringUtils.hasText(generatedBeanName)) {
		throw new BeanDefinitionStoreException("Unnamed bean definition specifies neither " +
				"'class' nor 'parent' nor 'factory-bean' - can't generate bean name");
	}

	String id = generatedBeanName;
	if (isInnerBean) {
		// Inner bean: generate identity hashcode suffix.
		id = generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + ObjectUtils.getIdentityHexString(definition);
	}
	else {
		// Top-level bean: use plain class name.
		// Increase counter until the id is unique.
		int counter = -1;
		while (counter == -1 || registry.containsBeanDefinition(id)) {
			counter++;
			id = generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + counter;
		}
	}
	return id;
}
 
Example #24
Source File: EagleBeanParser.java    From eagle with Apache License 2.0 5 votes vote down vote up
@Override
protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) throws BeanDefinitionStoreException {
    String id = element.getAttribute("id");
    if (!Strings.isNullOrEmpty(id)) {
        return id;
    }
    id = element.getAttribute("name");
    if (!Strings.isNullOrEmpty(id)) {
        return id;
    }
    return parserContext.getReaderContext().generateBeanName(definition);
}
 
Example #25
Source File: PropertySourceAnnotationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void withEmptyResourceLocations() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(ConfigWithEmptyResourceLocations.class);
	try {
		ctx.refresh();
	}
	catch (BeanDefinitionStoreException ex) {
		assertTrue(ex.getCause() instanceof IllegalArgumentException);
	}
}
 
Example #26
Source File: AbstractBeanDefinitionReader.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@Override
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
	Assert.notNull(locations, "Location array must not be null");
	int counter = 0;
	for (String location : locations) {
		counter += loadBeanDefinitions(location);
	}
	return counter;
}
 
Example #27
Source File: AbstractBeanDefinitionParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public final BeanDefinition parse(Element element, ParserContext parserContext) {
	// 注释 3.10 实际自定义标签解析器调用的方法,在 parseInternal 方法中,调用了我们重载的方法
	AbstractBeanDefinition definition = parseInternal(element, parserContext);
	if (definition != null && !parserContext.isNested()) {
		try {
			String id = resolveId(element, definition, parserContext);
			if (!StringUtils.hasText(id)) {
				parserContext.getReaderContext().error(
						"Id is required for element '" + parserContext.getDelegate().getLocalName(element)
								+ "' when used as a top-level tag", element);
			}
			String[] aliases = null;
			if (shouldParseNameAsAliases()) {
				String name = element.getAttribute(NAME_ATTRIBUTE);
				if (StringUtils.hasLength(name)) {
					aliases = StringUtils.trimArrayElements(StringUtils.commaDelimitedListToStringArray(name));
				}
			}
			// 组装成 BeanDefinitionHolder
			BeanDefinitionHolder holder = new BeanDefinitionHolder(definition, id, aliases);
			// 注册 bean 信息
			registerBeanDefinition(holder, parserContext.getRegistry());
			if (shouldFireEvents()) {
				BeanComponentDefinition componentDefinition = new BeanComponentDefinition(holder);
				postProcessComponentDefinition(componentDefinition);
				parserContext.registerComponent(componentDefinition);
			}
		}
		catch (BeanDefinitionStoreException ex) {
			String msg = ex.getMessage();
			parserContext.getReaderContext().error((msg != null ? msg : ex.toString()), element);
			return null;
		}
	}
	return definition;
}
 
Example #28
Source File: CaptchaSecurityService.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Default constructor.
 *
 * Gets the captchaValidator from the captcha plugin. If the validator is missing, sets available to false;
 */
public CaptchaSecurityService( )
{
    try
    {
        // first check if captchaValidator bean is available in the jcaptcha plugin context
        _captchaService = SpringContextService.getBean( "captcha.captchaService" );
        _bAvailable = _captchaService != null;
    }
    catch( CannotLoadBeanClassException | NoSuchBeanDefinitionException | BeanDefinitionStoreException e )
    {
        _bAvailable = false;
    }
}
 
Example #29
Source File: AbstractBeanDefinitionReader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
	Assert.notNull(resources, "Resource array must not be null");
	int counter = 0;
	for (Resource resource : resources) {
		counter += loadBeanDefinitions(resource);
	}
	return counter;
}
 
Example #30
Source File: AbstractBeanDefinitionReader.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
	Assert.notNull(locations, "Location array must not be null");
	int count = 0;
	for (String location : locations) {
		count += loadBeanDefinitions(location);
	}
	return count;
}