/** * 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); } } }
@Override public void afterPropertiesSet() throws Exception { if (configLocation == null) { return; } Resource resource = resourceLoader.getResource(configLocation); try { this.configMap = (Map<String, CacheConfig>) CacheConfig.fromJSON(resource.getInputStream()); } catch (IOException e) { // try to read yaml try { this.configMap = (Map<String, CacheConfig>) CacheConfig.fromYAML(resource.getInputStream()); } catch (IOException e1) { throw new BeanDefinitionStoreException( "Could not parse cache configuration at [" + configLocation + "]", e1); } } }
@Test public void testInitServletConfig() { /* * we fail if safeServlet propogates exception we rely on the underlying * DispatcherServlet throwing an exception when init'ed in this way * without the servlet name having been set and without there being a * -servlet.xml that it can find on the classpath. */ this.safeServlet.init(this.mockConfig); /* * here we test that the particular exception stored by the underlying * DispatcherServlet has been stored into the ServetContext as an * attribute as advertised by SafeDispatcherServlet. we rely on knowing * the particular exception that the underlying DispatcherServlet throws * under these circumstances; */ BeanDefinitionStoreException bdse = (BeanDefinitionStoreException) this.mockContext .getAttribute(SafeDispatcherServlet.CAUGHT_THROWABLE_KEY); assertNotNull(bdse); }
public static BeanDefinitionHolder register(Element ele, BeanDefinitionHolder bdHolder, ParserContext parserContext) { if (bdHolder != null) { String name = bdHolder.getBeanName(); checkReservedName(name, ele, parserContext); checkUniqueName(name, parserContext.getRegistry()); try { // add non-lenient constructor resolution BeanDefinition beanDefinition = bdHolder.getBeanDefinition(); if (beanDefinition instanceof AbstractBeanDefinition) { AbstractBeanDefinition abd = (AbstractBeanDefinition) beanDefinition; abd.setLenientConstructorResolution(false); abd.setNonPublicAccessAllowed(false); } // Register the final decorated instance. BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, parserContext.getRegistry()); } catch (BeanDefinitionStoreException ex) { parserContext.getReaderContext().error( "Failed to register bean definition with name '" + bdHolder.getBeanName() + "'", ele, ex); } // register component (and send registration events) parserContext.registerComponent(new BeanComponentDefinition(bdHolder)); } return bdHolder; }
/** * Generates a Blueprint specific bean name. * * @param definition * @param registry * @param isInnerBean * @return * @throws BeanDefinitionStoreException */ public static String generateBlueprintBeanName(BeanDefinition definition, BeanDefinitionRegistry registry, boolean isInnerBean) throws BeanDefinitionStoreException { String initialName = BLUEPRINT_GENERATED_NAME_PREFIX + BeanDefinitionReaderUtils.generateBeanName(definition, registry, isInnerBean); String generatedName = initialName; int counter = 0; while (registry.containsBeanDefinition(generatedName)) { generatedName = initialName + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + counter; counter++; } return generatedName; }
/** * 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 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; }
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; }
public void parse(Set<BeanDefinitionHolder> configCandidates) { for (BeanDefinitionHolder holder : configCandidates) { BeanDefinition bd = holder.getBeanDefinition(); try { if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) { parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName()); } else { parse(bd.getBeanClassName(), holder.getBeanName()); } } catch (IOException ex) { throw new BeanDefinitionStoreException("Failed to load bean class: " + bd.getBeanClassName(), ex); } } processDeferredImportSelectors(); }
/** * 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 aliase : aliases) { registry.registerAlias(beanName, aliase); } } }
/** * 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); } }
/** * Check the given merged bean definition, * potentially throwing validation exceptions. * @param mbd the merged bean definition to check * @param beanName the name of the bean * @param args the arguments for bean creation, if any * @throws BeanDefinitionStoreException in case of validation failure */ protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, Object[] args) throws BeanDefinitionStoreException { // check if bean definition is not abstract if (mbd.isAbstract()) { throw new BeanIsAbstractException(beanName); } // Check validity of the usage of the args parameter. This can // only be used for prototypes constructed via a factory method. if (args != null && !mbd.isPrototype()) { throw new BeanDefinitionStoreException( "Can only specify arguments for the getBean method when referring to a prototype bean definition"); } }
/** * 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)); } }
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); }
/** * 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); } }
public List<Resource> findInterestResources(String basePackage) { String[] packages = StringUtils.tokenizeToStringArray(basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); List<Resource> allResource = new LinkedList<Resource>(); try { for (String pack : packages) { String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolveBasePackage(pack) + "/" + this.resourcePattern; Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath); allResource.addAll(Arrays.asList(resources)); } } catch (IOException ex) { throw new BeanDefinitionStoreException("扫描ClassPath的时候I/O资源错误", ex); } return allResource; }
@Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { doBeforeParse(element); super.doParse(element, parserContext, builder); // now lets parse the routes with JAXB Binder<Node> binder; try { binder = getJaxbContext().createBinder(); } catch (JAXBException e) { throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e); } Object value = parseUsingJaxb(element, parserContext, binder); if (value instanceof CamelRouteContextFactoryBean) { CamelRouteContextFactoryBean factoryBean = (CamelRouteContextFactoryBean) value; builder.addPropertyValue("routes", factoryBean.getRoutes()); } // lets inject the namespaces into any namespace aware POJOs injectNamespaces(element, binder); }
@Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { doBeforeParse(element); super.doParse(element, parserContext, builder); // now lets parse the routes with JAXB Binder<Node> binder; try { binder = getJaxbContext().createBinder(); } catch (JAXBException e) { throw new BeanDefinitionStoreException("Failed to create the JAXB binder", e); } Object value = parseUsingJaxb(element, parserContext, binder); if (value instanceof CamelEndpointFactoryBean) { CamelEndpointFactoryBean factoryBean = (CamelEndpointFactoryBean) value; builder.addPropertyValue("properties", factoryBean.getProperties()); } }
@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 } }
public INaviModuleContext initModule() { try { status = ContextStatus.PREPARING; cxt = new NaviClassPathXmlApplicationContext(new String[]{moduleNm + ".xml"}, true); } catch (BeanDefinitionStoreException e) { if (e.getCause() instanceof FileNotFoundException) { throw new BeanDefinitionStoreException("no module " + moduleNm + " is loaded!"); } throw e; } finally { status = ContextStatus.NORMAL; } return this; }
@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")); } }
@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")); } }
@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 } }
/** * 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; }
@Override protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) throws BeanDefinitionStoreException { String id = super.resolveId(element, definition, parserContext); validateServiceReferences(element, id, parserContext); return id; }
@Override protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) throws BeanDefinitionStoreException { String id = element.getAttribute(ID_ATTRIBUTE); if (!StringUtils.hasText(id)) { id = generateBeanName("", definition, parserContext); } return id; }
@Override protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) throws BeanDefinitionStoreException { String id = ParsingUtils.resolveId(element, definition, parserContext, shouldGenerateId(), shouldGenerateIdAsFallback()); validateServiceReferences(element, id, parserContext); return id; }
private void processDeferredImportSelectors() { Collections.sort(this.deferredImportSelectors, DEFERRED_IMPORT_COMPARATOR); for (DeferredImportSelectorHolder deferredImport : this.deferredImportSelectors) { try { ConfigurationClass configClass = deferredImport.getConfigurationClass(); String[] imports = deferredImport.getImportSelector().selectImports(configClass.getMetadata()); processImports(configClass, asSourceClass(configClass), asSourceClasses(imports), false); } catch (Exception ex) { throw new BeanDefinitionStoreException("Failed to load bean class: ", ex); } } this.deferredImportSelectors.clear(); }
/** * 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; }
/** * Register bean definitions contained in a ResourceBundle. * <p>Similar syntax as for a Map. This method is useful to enable * standard Java internationalization support. * @param rb the ResourceBundle to load from * @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 registerBeanDefinitions(ResourceBundle rb, String prefix) throws BeanDefinitionStoreException { // Simply create a map and call overloaded method. Map<String, Object> map = new HashMap<String, Object>(); Enumeration<String> keys = rb.getKeys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); map.put(key, rb.getObject(key)); } return registerBeanDefinitions(map, prefix); }
@Override public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException { Assert.hasText(beanName, "'beanName' must not be empty"); Assert.notNull(beanDefinition, "BeanDefinition must not be null"); this.beanDefinitionMap.put(beanName, beanDefinition); }