Search in sources :

Example 16 with BeanFactory

use of cn.taketoday.beans.factory.BeanFactory in project today-infrastructure by TAKETODAY.

the class BeanFactoryDataSourceLookupTests method testLookupSunnyDay.

@Test
public void testLookupSunnyDay() {
    BeanFactory beanFactory = mock(BeanFactory.class);
    StubDataSource expectedDataSource = new StubDataSource();
    given(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).willReturn(expectedDataSource);
    BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup();
    lookup.setBeanFactory(beanFactory);
    DataSource dataSource = lookup.getDataSource(DATASOURCE_BEAN_NAME);
    assertThat(dataSource).as("A DataSourceLookup implementation must *never* return null from " + "getDataSource(): this one obviously (and incorrectly) is").isNotNull();
    assertThat(dataSource).isSameAs(expectedDataSource);
}
Also used : BeanFactory(cn.taketoday.beans.factory.BeanFactory) DataSource(javax.sql.DataSource) Test(org.junit.jupiter.api.Test)

Example 17 with BeanFactory

use of cn.taketoday.beans.factory.BeanFactory in project today-infrastructure by TAKETODAY.

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 cn.taketoday.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}.
 * </ol>
 *
 * @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}
 */
@Nullable
public static DataSource retrieveDataSource(TestContext testContext, @Nullable 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 {
        // Look up single bean by type
        Map<String, DataSource> dataSources = BeanFactoryUtils.beansOfTypeIncludingAncestors(bf, 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(cn.taketoday.beans.factory.BeanFactory) PlatformTransactionManager(cn.taketoday.transaction.PlatformTransactionManager) BeansException(cn.taketoday.beans.BeansException) DataSource(javax.sql.DataSource) Nullable(cn.taketoday.lang.Nullable)

Example 18 with BeanFactory

use of cn.taketoday.beans.factory.BeanFactory in project today-framework by TAKETODAY.

the class AspectAutoProxyCreator method getInterceptor.

private MethodInterceptor getInterceptor(BeanDefinition aspectDef, @Nullable Method aspectMethod, MergedAnnotation<Advice> advice) {
    BeanFactory beanFactory = getFactory();
    if (aspectMethod == null) {
        // method interceptor
        if (!beanFactory.isTypeMatch(aspectDef.getBeanName(), MethodInterceptor.class)) {
            throw new ConfigurationException('[' + aspectDef.getBeanClassName() + "] must be implement: [" + MethodInterceptor.class.getName() + ']');
        }
        // aspect is a method interceptor
        return getMethodInterceptor(beanFactory, aspectDef);
    }
    // -----------------
    // invoke advice method that annotated: @AfterReturning @Around @Before @After @AfterThrowing
    Class<? extends MethodInterceptor> interceptor = advice.getClass("interceptor");
    if (interceptor == AbstractAnnotationMethodInterceptor.class || !MethodInterceptor.class.isAssignableFrom(interceptor)) {
        throw new ConfigurationException(interceptor + " must be implement: [" + AbstractAnnotationMethodInterceptor.class.getName() + "] or [" + MethodInterceptor.class.getName() + "]");
    }
    // exist in bean factory ?
    if (AnnotatedElementUtils.hasAnnotation(interceptor, Component.class)) {
        if (beanFactory instanceof BeanDefinitionRegistry) {
            BeanDefinition interceptorDef = ((BeanDefinitionRegistry) beanFactory).getBeanDefinition(interceptor);
            if (interceptorDef != null) {
                // exist in bean factory
                return getMethodInterceptor(beanFactory, interceptorDef);
            }
        } else {
            // just get bean
            MethodInterceptor ret = beanFactory.getBean(interceptor);
            if (ret != null) {
                return ret;
            }
        }
    }
    // dynamic parameters -> aspectMethod, beanName, beanFactory
    MethodInterceptor ret = DependencyInjectorAwareInstantiator.instantiate(interceptor, beanFactory, new Object[] { aspectMethod, aspectDef.getBeanName(), beanFactory });
    if (beanFactory instanceof AutowireCapableBeanFactory) {
        ((AutowireCapableBeanFactory) beanFactory).autowireBean(ret);
    }
    return ret;
}
Also used : SuppliedMethodInterceptor(cn.taketoday.aop.support.SuppliedMethodInterceptor) MethodInterceptor(org.aopalliance.intercept.MethodInterceptor) ConfigurationException(cn.taketoday.core.ConfigurationException) BeanFactory(cn.taketoday.beans.factory.BeanFactory) AutowireCapableBeanFactory(cn.taketoday.beans.factory.config.AutowireCapableBeanFactory) BeanDefinitionRegistry(cn.taketoday.beans.factory.support.BeanDefinitionRegistry) BeanDefinition(cn.taketoday.beans.factory.config.BeanDefinition) AnnotatedBeanDefinition(cn.taketoday.beans.factory.annotation.AnnotatedBeanDefinition) AutowireCapableBeanFactory(cn.taketoday.beans.factory.config.AutowireCapableBeanFactory)

Example 19 with BeanFactory

use of cn.taketoday.beans.factory.BeanFactory in project today-framework by TAKETODAY.

the class AspectAutoProxyCreator method addCandidateAdvisors.

protected void addCandidateAdvisors() {
    BeanFactory beanFactory = getFactory();
    Set<String> aspectBeanNames = beanFactory.getBeanNamesForAnnotation(Aspect.class);
    for (String name : aspectBeanNames) {
        log.info("Found Aspect: [{}]", name);
        Class<?> aspectClass = beanFactory.getType(name);
        Assert.state(aspectClass != null, "Cannot determine bean type");
        BeanDefinition aspectDef = beanFactory.getBeanDefinition(name);
        // around
        if (MethodInterceptor.class.isAssignableFrom(aspectClass)) {
            Stream<MergedAnnotation<Advice>> adviceAttributes = getAdviceAttributes(aspectDef);
            addCandidateAdvisors(aspectDef, null, adviceAttributes);
        }
        // annotations: @AfterReturning @Around @Before @After @AfterThrowing
        Method[] declaredMethods = ReflectionUtils.getDeclaredMethods(aspectClass);
        for (Method aspectMethod : declaredMethods) {
            Stream<MergedAnnotation<Advice>> adviceAttributes = getAdviceAttributes(aspectMethod);
            addCandidateAdvisors(aspectDef, aspectMethod, adviceAttributes);
        }
    }
}
Also used : MergedAnnotation(cn.taketoday.core.annotation.MergedAnnotation) BeanFactory(cn.taketoday.beans.factory.BeanFactory) AutowireCapableBeanFactory(cn.taketoday.beans.factory.config.AutowireCapableBeanFactory) Method(java.lang.reflect.Method) BeanDefinition(cn.taketoday.beans.factory.config.BeanDefinition) AnnotatedBeanDefinition(cn.taketoday.beans.factory.annotation.AnnotatedBeanDefinition)

Example 20 with BeanFactory

use of cn.taketoday.beans.factory.BeanFactory in project today-framework by TAKETODAY.

the class JsonComponentModule method registerJsonComponents.

public void registerJsonComponents() {
    BeanFactory beanFactory = this.beanFactory;
    while (beanFactory != null) {
        addJsonBeans(beanFactory);
        beanFactory = (beanFactory instanceof HierarchicalBeanFactory) ? ((HierarchicalBeanFactory) beanFactory).getParentBeanFactory() : null;
    }
}
Also used : HierarchicalBeanFactory(cn.taketoday.beans.factory.HierarchicalBeanFactory) BeanFactory(cn.taketoday.beans.factory.BeanFactory) HierarchicalBeanFactory(cn.taketoday.beans.factory.HierarchicalBeanFactory)

Aggregations

BeanFactory (cn.taketoday.beans.factory.BeanFactory)80 Test (org.junit.jupiter.api.Test)60 ITestBean (cn.taketoday.beans.testfixture.beans.ITestBean)24 StandardBeanFactory (cn.taketoday.beans.factory.support.StandardBeanFactory)16 PlatformTransactionManager (cn.taketoday.transaction.PlatformTransactionManager)16 ClassPathXmlApplicationContext (cn.taketoday.context.support.ClassPathXmlApplicationContext)10 TestBean (cn.taketoday.beans.testfixture.beans.TestBean)8 CallCountingTransactionManager (cn.taketoday.testfixture.transaction.CallCountingTransactionManager)8 TransactionManager (cn.taketoday.transaction.TransactionManager)8 NestedTestBean (cn.taketoday.beans.testfixture.beans.NestedTestBean)6 List (java.util.List)6 DataSource (javax.sql.DataSource)6 Advised (cn.taketoday.aop.framework.Advised)4 BeansException (cn.taketoday.beans.BeansException)4 FatalBeanException (cn.taketoday.beans.FatalBeanException)4 NoSuchBeanDefinitionException (cn.taketoday.beans.factory.NoSuchBeanDefinitionException)4 Nullable (cn.taketoday.lang.Nullable)4 Collection (java.util.Collection)4 Set (java.util.Set)4 ServletException (jakarta.servlet.ServletException)3