Search in sources :

Example 11 with BeansException

use of org.springframework.beans.BeansException in project spring-framework by spring-projects.

the class CommonAnnotationBeanPostProcessorTests method testResourceInjectionWithResolvableDependencyType.

@Test
public void testResourceInjectionWithResolvableDependencyType() {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
    bpp.setBeanFactory(bf);
    bf.addBeanPostProcessor(bpp);
    RootBeanDefinition abd = new RootBeanDefinition(ExtendedResourceInjectionBean.class);
    abd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
    bf.registerBeanDefinition("annotatedBean", abd);
    RootBeanDefinition tbd = new RootBeanDefinition(TestBean.class);
    tbd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
    bf.registerBeanDefinition("testBean4", tbd);
    bf.registerResolvableDependency(BeanFactory.class, bf);
    bf.registerResolvableDependency(INestedTestBean.class, new ObjectFactory<Object>() {

        @Override
        public Object getObject() throws BeansException {
            return new NestedTestBean();
        }
    });
    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    Properties props = new Properties();
    props.setProperty("tb", "testBean4");
    ppc.setProperties(props);
    ppc.postProcessBeanFactory(bf);
    ExtendedResourceInjectionBean bean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
    INestedTestBean tb = bean.getTestBean6();
    assertNotNull(tb);
    ExtendedResourceInjectionBean anotherBean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
    assertNotSame(anotherBean, bean);
    assertNotSame(anotherBean.getTestBean6(), tb);
    String[] depBeans = bf.getDependenciesForBean("annotatedBean");
    assertEquals(1, depBeans.length);
    assertEquals("testBean4", depBeans[0]);
}
Also used : PropertyPlaceholderConfigurer(org.springframework.beans.factory.config.PropertyPlaceholderConfigurer) INestedTestBean(org.springframework.tests.sample.beans.INestedTestBean) NestedTestBean(org.springframework.tests.sample.beans.NestedTestBean) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) Properties(java.util.Properties) INestedTestBean(org.springframework.tests.sample.beans.INestedTestBean) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeansException(org.springframework.beans.BeansException) Test(org.junit.Test)

Example 12 with BeansException

use of org.springframework.beans.BeansException in project spring-framework by spring-projects.

the class TestContextTransactionUtils method retrieveDataSource.

/**
	 * Retrieve the {@link DataSource} to use for the supplied {@linkplain TestContext
	 * test context}.
	 * <p>The following algorithm is used to retrieve the {@code DataSource} from
	 * the {@link org.springframework.context.ApplicationContext ApplicationContext}
	 * of the supplied test context:
	 * <ol>
	 * <li>Look up the {@code DataSource} by type and name, if the supplied
	 * {@code name} is non-empty, throwing a {@link BeansException} if the named
	 * {@code DataSource} does not exist.
	 * <li>Attempt to look up the single {@code DataSource} by type.
	 * <li>Attempt to look up the <em>primary</em> {@code DataSource} by type.
	 * <li>Attempt to look up the {@code DataSource} by type and the
	 * {@linkplain #DEFAULT_DATA_SOURCE_NAME default data source name}.
	 * @param testContext the test context for which the {@code DataSource}
	 * should be retrieved; never {@code null}
	 * @param name the name of the {@code DataSource} to retrieve; may be {@code null}
	 * or <em>empty</em>
	 * @return the {@code DataSource} to use, or {@code null} if not found
	 * @throws BeansException if an error occurs while retrieving an explicitly
	 * named {@code DataSource}
	 */
public static DataSource retrieveDataSource(TestContext testContext, String name) {
    Assert.notNull(testContext, "TestContext must not be null");
    BeanFactory bf = testContext.getApplicationContext().getAutowireCapableBeanFactory();
    try {
        // look up by type and explicit name
        if (StringUtils.hasText(name)) {
            return bf.getBean(name, DataSource.class);
        }
    } catch (BeansException ex) {
        logger.error(String.format("Failed to retrieve DataSource named '%s' for test context %s", name, testContext), ex);
        throw ex;
    }
    try {
        if (bf instanceof ListableBeanFactory) {
            ListableBeanFactory lbf = (ListableBeanFactory) bf;
            // look up single bean by type
            Map<String, DataSource> dataSources = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, DataSource.class);
            if (dataSources.size() == 1) {
                return dataSources.values().iterator().next();
            }
            try {
                // look up single bean by type, with support for 'primary' beans
                return bf.getBean(DataSource.class);
            } catch (BeansException ex) {
                logBeansException(testContext, ex, PlatformTransactionManager.class);
            }
        }
        // look up by type and default name
        return bf.getBean(DEFAULT_DATA_SOURCE_NAME, DataSource.class);
    } catch (BeansException ex) {
        logBeansException(testContext, ex, DataSource.class);
        return null;
    }
}
Also used : BeanFactory(org.springframework.beans.factory.BeanFactory) ListableBeanFactory(org.springframework.beans.factory.ListableBeanFactory) ListableBeanFactory(org.springframework.beans.factory.ListableBeanFactory) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) BeansException(org.springframework.beans.BeansException) DataSource(javax.sql.DataSource)

Example 13 with BeansException

use of org.springframework.beans.BeansException in project spring-framework by spring-projects.

the class TestContextTransactionUtils method retrieveTransactionManager.

/**
	 * Retrieve the {@linkplain PlatformTransactionManager transaction manager}
	 * to use for the supplied {@linkplain TestContext test context}.
	 * <p>The following algorithm is used to retrieve the transaction manager
	 * from the {@link org.springframework.context.ApplicationContext ApplicationContext}
	 * of the supplied test context:
	 * <ol>
	 * <li>Look up the transaction manager by type and explicit name, if the supplied
	 * {@code name} is non-empty, throwing a {@link BeansException} if the named
	 * transaction manager does not exist.
	 * <li>Attempt to look up the single transaction manager by type.
	 * <li>Attempt to look up the <em>primary</em> transaction manager by type.
	 * <li>Attempt to look up the transaction manager via a
	 * {@link TransactionManagementConfigurer}, if present.
	 * <li>Attempt to look up the transaction manager by type and the
	 * {@linkplain #DEFAULT_TRANSACTION_MANAGER_NAME default transaction manager
	 * name}.
	 * @param testContext the test context for which the transaction manager
	 * should be retrieved; never {@code null}
	 * @param name the name of the transaction manager to retrieve; may be
	 * {@code null} or <em>empty</em>
	 * @return the transaction manager to use, or {@code null} if not found
	 * @throws BeansException if an error occurs while retrieving an explicitly
	 * named transaction manager
	 * @throws IllegalStateException if more than one TransactionManagementConfigurer
	 * exists in the ApplicationContext
	 */
public static PlatformTransactionManager retrieveTransactionManager(TestContext testContext, String name) {
    Assert.notNull(testContext, "TestContext must not be null");
    BeanFactory bf = testContext.getApplicationContext().getAutowireCapableBeanFactory();
    try {
        // look up by type and explicit name
        if (StringUtils.hasText(name)) {
            return bf.getBean(name, PlatformTransactionManager.class);
        }
    } catch (BeansException ex) {
        logger.error(String.format("Failed to retrieve transaction manager named '%s' for test context %s", name, testContext), ex);
        throw ex;
    }
    try {
        if (bf instanceof ListableBeanFactory) {
            ListableBeanFactory lbf = (ListableBeanFactory) bf;
            // look up single bean by type
            Map<String, PlatformTransactionManager> txMgrs = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, PlatformTransactionManager.class);
            if (txMgrs.size() == 1) {
                return txMgrs.values().iterator().next();
            }
            try {
                // look up single bean by type, with support for 'primary' beans
                return bf.getBean(PlatformTransactionManager.class);
            } catch (BeansException ex) {
                logBeansException(testContext, ex, PlatformTransactionManager.class);
            }
            // look up single TransactionManagementConfigurer
            Map<String, TransactionManagementConfigurer> configurers = BeanFactoryUtils.beansOfTypeIncludingAncestors(lbf, TransactionManagementConfigurer.class);
            Assert.state(configurers.size() <= 1, "Only one TransactionManagementConfigurer may exist in the ApplicationContext");
            if (configurers.size() == 1) {
                return configurers.values().iterator().next().annotationDrivenTransactionManager();
            }
        }
        // look up by type and default name
        return bf.getBean(DEFAULT_TRANSACTION_MANAGER_NAME, PlatformTransactionManager.class);
    } catch (BeansException ex) {
        logBeansException(testContext, ex, PlatformTransactionManager.class);
        return null;
    }
}
Also used : BeanFactory(org.springframework.beans.factory.BeanFactory) ListableBeanFactory(org.springframework.beans.factory.ListableBeanFactory) TransactionManagementConfigurer(org.springframework.transaction.annotation.TransactionManagementConfigurer) ListableBeanFactory(org.springframework.beans.factory.ListableBeanFactory) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) BeansException(org.springframework.beans.BeansException)

Example 14 with BeansException

use of org.springframework.beans.BeansException in project spring-cloud-connectors by spring-cloud.

the class CloudServiceIntroducer method postProcessBeanFactory.

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    try {
        Constructor<?> ctor = serviceConnectorFactoryType.getConstructor(String.class, ServiceConnectorConfig.class);
        AbstractCloudServiceConnectorFactory<?> serviceFactory = (AbstractCloudServiceConnectorFactory<?>) ctor.newInstance(serviceId, serviceConnectorConfig);
        serviceFactory.setServiceConnectorType((Class) serviceConnectorType);
        serviceFactory.setBeanFactory(beanFactory);
        serviceFactory.afterPropertiesSet();
        // id is the beanId if specified, otherwise the serviceId
        if (StringUtils.hasText(beanId)) {
            beanFactory.registerSingleton(beanId, serviceFactory);
        } else {
            beanFactory.registerSingleton(serviceFactory.getServiceId(), serviceFactory);
        }
    } catch (Exception ex) {
        throw new BeanCreationException("Error registering service factory", ex);
    }
}
Also used : BeanCreationException(org.springframework.beans.factory.BeanCreationException) AbstractCloudServiceConnectorFactory(org.springframework.cloud.service.AbstractCloudServiceConnectorFactory) BeansException(org.springframework.beans.BeansException) BeanCreationException(org.springframework.beans.factory.BeanCreationException)

Example 15 with BeansException

use of org.springframework.beans.BeansException in project spring-framework by spring-projects.

the class GenericFilterBean method init.

/**
	 * Standard way of initializing this filter.
	 * Map config parameters onto bean properties of this filter, and
	 * invoke subclass initialization.
	 * @param filterConfig the configuration for this filter
	 * @throws ServletException if bean properties are invalid (or required
	 * properties are missing), or if subclass initialization fails.
	 * @see #initFilterBean
	 */
@Override
public final void init(FilterConfig filterConfig) throws ServletException {
    Assert.notNull(filterConfig, "FilterConfig must not be null");
    if (logger.isDebugEnabled()) {
        logger.debug("Initializing filter '" + filterConfig.getFilterName() + "'");
    }
    this.filterConfig = filterConfig;
    // Set bean properties from init parameters.
    try {
        PropertyValues pvs = new FilterConfigPropertyValues(filterConfig, this.requiredProperties);
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
        ResourceLoader resourceLoader = new ServletContextResourceLoader(filterConfig.getServletContext());
        bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.environment));
        initBeanWrapper(bw);
        bw.setPropertyValues(pvs, true);
    } catch (BeansException ex) {
        String msg = "Failed to set bean properties on filter '" + filterConfig.getFilterName() + "': " + ex.getMessage();
        logger.error(msg, ex);
        throw new NestedServletException(msg, ex);
    }
    // Let subclasses do whatever initialization they like.
    initFilterBean();
    if (logger.isDebugEnabled()) {
        logger.debug("Filter '" + filterConfig.getFilterName() + "' configured successfully");
    }
}
Also used : ResourceLoader(org.springframework.core.io.ResourceLoader) ServletContextResourceLoader(org.springframework.web.context.support.ServletContextResourceLoader) BeanWrapper(org.springframework.beans.BeanWrapper) MutablePropertyValues(org.springframework.beans.MutablePropertyValues) PropertyValues(org.springframework.beans.PropertyValues) NestedServletException(org.springframework.web.util.NestedServletException) ResourceEditor(org.springframework.core.io.ResourceEditor) ServletContextResourceLoader(org.springframework.web.context.support.ServletContextResourceLoader) BeansException(org.springframework.beans.BeansException)

Aggregations

BeansException (org.springframework.beans.BeansException)64 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)14 BeanWrapper (org.springframework.beans.BeanWrapper)11 Test (org.junit.Test)10 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)9 GenericApplicationContext (org.springframework.context.support.GenericApplicationContext)9 BeanCreationException (org.springframework.beans.factory.BeanCreationException)8 MalformedURLException (java.net.MalformedURLException)7 ArrayList (java.util.ArrayList)7 XmlBeanDefinitionReader (org.springframework.beans.factory.xml.XmlBeanDefinitionReader)7 ApplicationContext (org.springframework.context.ApplicationContext)7 Map (java.util.Map)6 IgniteConfiguration (org.apache.ignite.configuration.IgniteConfiguration)5 BeanWrapperImpl (org.springframework.beans.BeanWrapperImpl)5 IOException (java.io.IOException)4 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)4 FileSystemXmlApplicationContext (org.springframework.context.support.FileSystemXmlApplicationContext)4 UrlResource (org.springframework.core.io.UrlResource)4 File (java.io.File)3 HashMap (java.util.HashMap)3