List of usage examples for org.springframework.beans.factory.support DefaultListableBeanFactory getBeanDefinition
@Override public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException
From source file:com.helpinput.spring.refresher.SessiontRefresher.java
@Override public void refresh(ApplicationContext context, Map<Class<?>, ScanedType> scanedClasses) { boolean needRefreshSessionFactory = false; for (Entry<Class<?>, ScanedType> entry : scanedClasses.entrySet()) { if (entry.getValue().getValue() > ScanedType.SAME.getValue() && entry.getKey().getAnnotation(Entity.class) != null) { needRefreshSessionFactory = true; break; }/* ww w .ja v a 2 s . co m*/ } if (needRefreshSessionFactory) { DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) ((AbstractApplicationContext) context) .getBeanFactory(); //testUserManager(dlbf); final String sessionFactory = "sessionFactory"; final String annotatedClasses = "annotatedClasses"; final String setSessionFactory = "setSessionFactory"; BeanDefinition oldSessionFactoryDef = dlbf.getBeanDefinition(sessionFactory); if (oldSessionFactoryDef != null) { dlbf.removeBeanDefinition(sessionFactory); MutablePropertyValues propertyValues = oldSessionFactoryDef.getPropertyValues(); PropertyValue oldPropertyValue = propertyValues.getPropertyValue(annotatedClasses); propertyValues.removePropertyValue(annotatedClasses); BeanDefinition newSessionFactoryDef = BeanDefinitionBuilder .rootBeanDefinition(oldSessionFactoryDef.getBeanClassName()).getBeanDefinition(); List<PropertyValue> propertyValueList = newSessionFactoryDef.getPropertyValues() .getPropertyValueList(); propertyValueList.addAll(propertyValues.getPropertyValueList()); propertyValueList.add(new PropertyValue(annotatedClasses, getManageList(dlbf, oldPropertyValue))); dlbf.registerBeanDefinition(sessionFactory, newSessionFactoryDef); SessionFactory sessionFactoryImpl = (SessionFactory) dlbf.getBean(sessionFactory); String[] beanNames = dlbf.getBeanDefinitionNames(); for (String beanName : beanNames) { BeanDefinition beanDefinition = dlbf.getBeanDefinition(beanName); PropertyValues pValues = beanDefinition.getPropertyValues(); if (pValues.getPropertyValue(sessionFactory) != null) { Object theBean = dlbf.getBean(beanName); Method method = Utils.findMethod(theBean, setSessionFactory, sessionFactoryImpl); if (method != null) Utils.InvokedMethod(theBean, method, sessionFactoryImpl); } } } } }
From source file:org.codehaus.griffon.runtime.spring.GriffonRuntimeConfigurator.java
private void doPostResourceConfiguration(GriffonApplication application, RuntimeSpringConfiguration springConfig) { ClassLoader classLoader = ApplicationClassLoader.get(); String resourceName = SPRING_RESOURCES_XML; try {//from w w w . j a va 2 s .c o m Resource springResources = new ClassPathResource(resourceName); if (springResources != null && springResources.exists()) { if (LOG.isDebugEnabled()) LOG.debug( "[RuntimeConfiguration] Configuring additional beans from " + springResources.getURL()); DefaultListableBeanFactory xmlBf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xmlBf).loadBeanDefinitions(springResources); xmlBf.setBeanClassLoader(classLoader); String[] beanNames = xmlBf.getBeanDefinitionNames(); if (LOG.isDebugEnabled()) LOG.debug("[RuntimeConfiguration] Found [" + beanNames.length + "] beans to configure"); for (String beanName : beanNames) { BeanDefinition bd = xmlBf.getBeanDefinition(beanName); final String beanClassName = bd.getBeanClassName(); Class<?> beanClass = beanClassName == null ? null : ClassUtils.forName(beanClassName, classLoader); springConfig.addBeanDefinition(beanName, bd); String[] aliases = xmlBf.getAliases(beanName); for (String alias : aliases) { springConfig.addAlias(alias, beanName); } if (beanClass != null) { if (BeanFactoryPostProcessor.class.isAssignableFrom(beanClass)) { ((ConfigurableApplicationContext) springConfig.getUnrefreshedApplicationContext()) .addBeanFactoryPostProcessor( (BeanFactoryPostProcessor) xmlBf.getBean(beanName)); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("[RuntimeConfiguration] " + resourceName + " not found. Skipping configuration."); } } catch (Exception ex) { LOG.error("[RuntimeConfiguration] Unable to perform post initialization config: " + resourceName, sanitize(ex)); } loadSpringGroovyResources(springConfig, application); }
From source file:com.laxser.blitz.web.impl.module.ModulesBuilderImpl.java
private void registerBeanDefinitions(XmlWebApplicationContext context, List<Class<?>> classes) { DefaultListableBeanFactory bf = (DefaultListableBeanFactory) context.getBeanFactory(); String[] definedClasses = new String[bf.getBeanDefinitionCount()]; String[] definitionNames = bf.getBeanDefinitionNames(); for (int i = 0; i < definedClasses.length; i++) { String name = definitionNames[i]; definedClasses[i] = bf.getBeanDefinition(name).getBeanClassName(); }// ww w.j a v a 2s . c o m for (Class<?> clazz : classes) { // ? if (!isCandidate(clazz)) { continue; } // bean String clazzName = clazz.getName(); if (ArrayUtils.contains(definedClasses, clazzName)) { if (logger.isDebugEnabled()) { logger.debug( "Ignores bean definition because it has been exist in context: " + clazz.getName()); } continue; } // String beanName = null; if (StringUtils.isEmpty(beanName) && clazz.isAnnotationPresent(Component.class)) { beanName = clazz.getAnnotation(Component.class).value(); } if (StringUtils.isEmpty(beanName) && clazz.isAnnotationPresent(Resource.class)) { beanName = clazz.getAnnotation(Resource.class).name(); } if (StringUtils.isEmpty(beanName) && clazz.isAnnotationPresent(Service.class)) { beanName = clazz.getAnnotation(Service.class).value(); } if (StringUtils.isEmpty(beanName)) { beanName = AUTO_BEAN_NAME_PREFIX + clazz.getName(); } bf.registerBeanDefinition(beanName, new AnnotatedGenericBeanDefinition(clazz)); } }
From source file:co.paralleluniverse.common.spring.SpringContainerHelper.java
public static ConfigurableApplicationContext createContext(String defaultDomain, Resource xmlResource, Object properties, BeanFactoryPostProcessor beanFactoryPostProcessor) { LOG.info("JAVA: {} {}, {}", new Object[] { System.getProperty("java.runtime.name"), System.getProperty("java.runtime.version"), System.getProperty("java.vendor") }); LOG.info("OS: {} {}, {}", new Object[] { System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch") }); LOG.info("DIR: {}", System.getProperty("user.dir")); final DefaultListableBeanFactory beanFactory = createBeanFactory(); final GenericApplicationContext context = new GenericApplicationContext(beanFactory); context.registerShutdownHook();// w w w . j a v a 2 s . c o m final PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer(); propertyPlaceholderConfigurer .setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE); if (properties != null) { if (properties instanceof Resource) propertyPlaceholderConfigurer.setLocation((Resource) properties); else if (properties instanceof Properties) propertyPlaceholderConfigurer.setProperties((Properties) properties); else throw new IllegalArgumentException( "Properties argument - " + properties + " - is of an unhandled type"); } context.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer); // MBean exporter //final MBeanExporter mbeanExporter = new AnnotationMBeanExporter(); //mbeanExporter.setServer(ManagementFactory.getPlatformMBeanServer()); //beanFactory.registerSingleton("mbeanExporter", mbeanExporter); context.registerBeanDefinition("mbeanExporter", getMBeanExporterBeanDefinition(defaultDomain)); // inject bean names into components context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() { @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { for (String beanName : beanFactory.getBeanDefinitionNames()) { try { final BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); if (beanDefinition.getBeanClassName() != null) { // van be null for factory methods final Class<?> beanClass = Class.forName(beanDefinition.getBeanClassName()); if (Component.class.isAssignableFrom(beanClass)) beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, beanName); } } catch (Exception ex) { LOG.error("Error loading bean " + beanName + " definition.", ex); throw new Error(ex); } } } }); if (beanFactoryPostProcessor != null) context.addBeanFactoryPostProcessor(beanFactoryPostProcessor); beanFactory.registerCustomEditor(org.w3c.dom.Element.class, co.paralleluniverse.common.util.DOMElementProprtyEditor.class); final Map<String, Object> beans = new HashMap<String, Object>(); beanFactory.addBeanPostProcessor(new BeanPostProcessor() { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { LOG.info("Loading bean {} [{}]", beanName, bean.getClass().getName()); beans.put(beanName, bean); if (bean instanceof Service) { final BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); Collection<String> dependencies = getBeanDependencies(beanDefinition); for (String dependeeName : dependencies) { Object dependee = beanFactory.getBean(dependeeName); if (dependee instanceof Service) { ((Service) dependee).addDependedBy((Service) bean); ((Service) bean).addDependsOn((Service) dependee); } } } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { LOG.info("Bean {} [{}] loaded", beanName, bean.getClass().getName()); return bean; } }); final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory); xmlReader.loadBeanDefinitions(xmlResource); // start container context.refresh(); // Call .postInit() on all Components // There's probably a better way to do this try { for (Map.Entry<String, Object> entry : beans.entrySet()) { final String beanName = entry.getKey(); final Object bean = entry.getValue(); if (bean instanceof Component) { LOG.info("Performing post-initialization on bean {} [{}]", beanName, bean.getClass().getName()); ((Component) bean).postInit(); } } } catch (Exception e) { throw Throwables.propagate(e); } return context; }
From source file:com.mtgi.analytics.aop.config.TemplateBeanDefinitionParser.java
/** * <p>Load the template BeanDefinition and call {@link #transform(ConfigurableListableBeanFactory, BeanDefinition, Element, ParserContext)} * to apply runtime configuration value to it. <code>builder</code> will be configured to instantiate the bean * in the Spring context that we are parsing.</p> * /*from w w w. j ava2s . com*/ * <p>During parsing, an instance of {@link TemplateBeanDefinitionParser.TemplateComponentDefinition} is pushed onto <code>ParserContext</code> so * that nested tags can access the enclosing template configuration with a call to {@link #findEnclosingTemplateFactory(ParserContext)}. * Subclasses can override {@link #newComponentDefinition(String, Object, DefaultListableBeanFactory)} to provide a * subclass of {@link TemplateBeanDefinitionParser.TemplateComponentDefinition} to the parser context if necessary.</p> */ @Override protected final void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { //if we have multiple nested bean definitions, we only parse the template factory //once. this allows configuration changes made by enclosing bean parsers to be inherited //by contained beans, which is quite useful. DefaultListableBeanFactory templateFactory = findEnclosingTemplateFactory(parserContext); TemplateComponentDefinition tcd = null; if (templateFactory == null) { //no nesting -- load the template XML configuration from the classpath. final BeanFactory parentFactory = (BeanFactory) parserContext.getRegistry(); templateFactory = new DefaultListableBeanFactory(parentFactory); //load template bean definitions DefaultResourceLoader loader = new DefaultResourceLoader(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(templateFactory); reader.setResourceLoader(loader); reader.setEntityResolver(new ResourceEntityResolver(loader)); reader.loadBeanDefinitions(templateResource); //propagate factory post-processors from the source factory into the template //factory. BeanDefinition ppChain = new RootBeanDefinition(ChainingBeanFactoryPostProcessor.class); ppChain.getPropertyValues().addPropertyValue("targetFactory", templateFactory); parserContext.getReaderContext().registerWithGeneratedName(ppChain); //push component definition onto the parser stack for the benefit of //nested bean definitions. tcd = newComponentDefinition(element.getNodeName(), parserContext.extractSource(element), templateFactory); parserContext.pushContainingComponent(tcd); } try { //allow subclasses to apply overrides to the template bean definition. BeanDefinition def = templateFactory.getBeanDefinition(templateId); transform(templateFactory, def, element, parserContext); //setup our factory bean to instantiate the modified bean definition upon request. builder.addPropertyValue("beanFactory", templateFactory); builder.addPropertyValue("beanName", templateId); builder.getRawBeanDefinition().setAttribute("id", def.getAttribute("id")); } finally { if (tcd != null) parserContext.popContainingComponent(); } }
From source file:org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator.java
private void doPostResourceConfiguration(GrailsApplication app, RuntimeSpringConfiguration springConfig) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); String resourceName = null;/*from w ww .java2 s . c o m*/ try { Resource springResources; if (app.isWarDeployed()) { resourceName = GrailsRuntimeConfigurator.SPRING_RESOURCES_XML; springResources = parent.getResource(resourceName); } else { resourceName = DEVELOPMENT_SPRING_RESOURCES_XML; ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(); springResources = patternResolver.getResource(resourceName); } if (springResources != null && springResources.exists()) { if (LOG.isDebugEnabled()) LOG.debug( "[RuntimeConfiguration] Configuring additional beans from " + springResources.getURL()); DefaultListableBeanFactory xmlBf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xmlBf).loadBeanDefinitions(springResources); xmlBf.setBeanClassLoader(classLoader); String[] beanNames = xmlBf.getBeanDefinitionNames(); if (LOG.isDebugEnabled()) LOG.debug("[RuntimeConfiguration] Found [" + beanNames.length + "] beans to configure"); for (String beanName : beanNames) { BeanDefinition bd = xmlBf.getBeanDefinition(beanName); final String beanClassName = bd.getBeanClassName(); Class<?> beanClass = beanClassName == null ? null : ClassUtils.forName(beanClassName, classLoader); springConfig.addBeanDefinition(beanName, bd); String[] aliases = xmlBf.getAliases(beanName); for (String alias : aliases) { springConfig.addAlias(alias, beanName); } if (beanClass != null) { if (BeanFactoryPostProcessor.class.isAssignableFrom(beanClass)) { ((ConfigurableApplicationContext) springConfig.getUnrefreshedApplicationContext()) .addBeanFactoryPostProcessor( (BeanFactoryPostProcessor) xmlBf.getBean(beanName)); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("[RuntimeConfiguration] " + resourceName + " not found. Skipping configuration."); } } catch (Exception ex) { LOG.error("[RuntimeConfiguration] Unable to perform post initialization config: " + resourceName, ex); } GrailsRuntimeConfigurator.loadSpringGroovyResources(springConfig, app); }
From source file:org.grails.web.servlet.context.support.GrailsRuntimeConfigurator.java
protected void doPostResourceConfiguration(GrailsApplication app, RuntimeSpringConfiguration springConfig) { ClassLoader classLoader = app.getClassLoader(); String resourceName = null;//from www . j a va 2 s . c om try { Resource springResources; if (app.isWarDeployed()) { resourceName = GrailsRuntimeConfigurator.SPRING_RESOURCES_XML; springResources = parent.getResource(resourceName); } else { resourceName = DEVELOPMENT_SPRING_RESOURCES_XML; ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(); springResources = patternResolver.getResource(resourceName); } if (springResources != null && springResources.exists()) { if (LOG.isDebugEnabled()) LOG.debug( "[RuntimeConfiguration] Configuring additional beans from " + springResources.getURL()); DefaultListableBeanFactory xmlBf = new OptimizedAutowireCapableBeanFactory(); new XmlBeanDefinitionReader(xmlBf).loadBeanDefinitions(springResources); xmlBf.setBeanClassLoader(classLoader); String[] beanNames = xmlBf.getBeanDefinitionNames(); if (LOG.isDebugEnabled()) LOG.debug("[RuntimeConfiguration] Found [" + beanNames.length + "] beans to configure"); for (String beanName : beanNames) { BeanDefinition bd = xmlBf.getBeanDefinition(beanName); final String beanClassName = bd.getBeanClassName(); Class<?> beanClass = beanClassName == null ? null : ClassUtils.forName(beanClassName, classLoader); springConfig.addBeanDefinition(beanName, bd); String[] aliases = xmlBf.getAliases(beanName); for (String alias : aliases) { springConfig.addAlias(alias, beanName); } if (beanClass != null) { if (BeanFactoryPostProcessor.class.isAssignableFrom(beanClass)) { ((ConfigurableApplicationContext) springConfig.getUnrefreshedApplicationContext()) .addBeanFactoryPostProcessor( (BeanFactoryPostProcessor) xmlBf.getBean(beanName)); } } } } else if (LOG.isDebugEnabled()) { LOG.debug("[RuntimeConfiguration] " + resourceName + " not found. Skipping configuration."); } } catch (Exception ex) { LOG.error("[RuntimeConfiguration] Unable to perform post initialization config: " + resourceName, ex); } GrailsRuntimeConfigurator.loadSpringGroovyResources(springConfig, app); }
From source file:org.springframework.beans.factory.DefaultListableBeanFactoryTests.java
@Test public void testExplicitScopeInheritanceForChildBeanDefinitions() throws Exception { String theChildScope = "bonanza!"; RootBeanDefinition parent = new RootBeanDefinition(); parent.setScope(RootBeanDefinition.SCOPE_PROTOTYPE); AbstractBeanDefinition child = BeanDefinitionBuilder.childBeanDefinition("parent").getBeanDefinition(); child.setBeanClass(TestBean.class); child.setScope(theChildScope);//from w w w. ja va 2s .co m DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); factory.registerBeanDefinition("parent", parent); factory.registerBeanDefinition("child", child); AbstractBeanDefinition def = (AbstractBeanDefinition) factory.getBeanDefinition("child"); assertEquals("Child 'scope' not overriding parent scope (it must).", theChildScope, def.getScope()); }
From source file:org.springframework.beans.factory.xml.XmlBeanFactoryTests.java
@Test public void testClassNotFoundWithNoBeanClassLoader() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); reader.setBeanClassLoader(null);// w w w .j av a 2 s. c o m reader.loadBeanDefinitions(CLASS_NOT_FOUND_CONTEXT); assertEquals("WhatALotOfRubbish", bf.getBeanDefinition("classNotFound").getBeanClassName()); }
From source file:org.springframework.beans.factory.xml.XmlBeanFactoryTests.java
@Test public void testNonLenientDependencyMatching() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("lenientDependencyTestBean"); bd.setLenientConstructorResolution(false); try {//from w w w .j ava 2 s . c om xbf.getBean("lenientDependencyTestBean"); fail("Should have thrown BeanCreationException"); } catch (BeanCreationException ex) { // expected ex.printStackTrace(); assertTrue(ex.getMostSpecificCause().getMessage().contains("Ambiguous")); } }