Java 类org.springframework.beans.factory.support.GenericBeanDefinition 实例源码

项目:jkami    文件:ClassPathMapperScanner.java   
@Override
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
    Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
    if (beanDefinitions.isEmpty()) {
        logger.warn("No  mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
    } else {
        for (BeanDefinitionHolder holder : beanDefinitions) {
            GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();
            if (logger.isDebugEnabled()) {
                logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '" + definition.getBeanClassName()
                        + "' mapperInterface");
            }
            definition.getPropertyValues().add("mapperProxy", getRegistry().getBeanDefinition("mapperProxy"));
            definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());
            definition.setBeanClass(MapperFactoryBean.class);
            definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
        }
    }
    return beanDefinitions;
}
项目:gemini.blueprint    文件:NestedDefinitionMetadataTest.java   
public void testOverallMetadata() throws Exception {

        BeanDefinition def = new GenericBeanDefinition();
        assertEquals(new SimpleComponentMetadata(null, def), new SimpleComponentMetadata("foo", def));

        Collection<ComponentMetadata> metadata = blueprintContainer.getMetadata(ComponentMetadata.class);

        for (ComponentMetadata componentMetadata : metadata) {
            if (componentMetadata instanceof ServiceReferenceMetadata) {
                System.out.println(componentMetadata.getId());
            }
        }
        // 1+1+3+4+4+5+3+1=22
        assertEquals(22, metadata.size());
        System.out.println(blueprintContainer.getComponentIds());
    }
项目:lams    文件:GroovyBeanDefinitionWrapper.java   
protected AbstractBeanDefinition createBeanDefinition() {
    AbstractBeanDefinition bd = new GenericBeanDefinition();
    bd.setBeanClass(this.clazz);
    if (!CollectionUtils.isEmpty(this.constructorArgs)) {
        ConstructorArgumentValues cav = new ConstructorArgumentValues();
        for (Object constructorArg : this.constructorArgs) {
            cav.addGenericArgumentValue(constructorArg);
        }
        bd.setConstructorArgumentValues(cav);
    }
    if (this.parentName != null) {
        bd.setParentName(this.parentName);
    }
    this.definitionWrapper = new BeanWrapperImpl(bd);
    return bd;
}
项目:dcmp    文件:SpringBeanFactory.java   
/**
 * Reloading spring bean
 *
 * @param clazz
 * @param initMethod
 * @param destroyMethod
 * @throws Exception
 */
public void reloadBean(Class<?> clazz, String initMethod, String destroyMethod) throws Exception {

    BeanDefinitionRegistry beanDefinitionRegistry = ((BeanDefinitionRegistry) this.beanFactory);
    String beanName = clazz.getSimpleName().substring(0, 1).toLowerCase() + clazz.getSimpleName().substring(1);

    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setBeanClass(clazz);
    beanDefinition.setAutowireCandidate(true);

    if (StringUtils.isNotBlank(initMethod)) {
        beanDefinition.setInitMethodName(initMethod);
    }

    if (StringUtils.isNotBlank(destroyMethod)) {
        beanDefinition.setDestroyMethodName(destroyMethod);
    }

    if (beanDefinitionRegistry.containsBeanDefinition(beanName)) {
        beanDefinitionRegistry.removeBeanDefinition(beanName);
    }

    beanDefinitionRegistry.registerBeanDefinition(beanName, beanDefinition);
    applicationContext.getBean(beanName);
}
项目:albedo-thrift    文件:ServiceStarter.java   
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    BeanDefinitionRegistry registry=(BeanDefinitionRegistry)beanFactory;
    CuratorFramework curatorFramework = beanFactory.getBean(CuratorFramework.class);
    ServiceRouter serviceRouter = beanFactory.getBean(ServiceRouter.class);
    for(Class clazz:list){
        GenericBeanDefinition definition=(GenericBeanDefinition) BeanDefinitionBuilder.genericBeanDefinition(clazz).getBeanDefinition();
        definition.getPropertyValues().addPropertyValue("innerClass",clazz);
        definition.getPropertyValues().addPropertyValue("factory",beanFactory);
        ServiceApi serviceApi = map.get(clazz.getName());
        definition.getPropertyValues().addPropertyValue("proccessName",serviceApi.getName());

        String path = "/"+clazz.getName()+"/"+ (serviceApi!=null ? serviceApi.getVersion() :
                ThriftConstant.DEFAULT_VERSION);
        ServiceDiscover serviceDiscover = new ZookeeperServiceDiscover(curatorFramework, path);

        definition.getPropertyValues().addPropertyValue("serverManager",
                new ServerManager(serviceDiscover, serviceRouter));

        definition.setBeanClass(ProxyFactoryBean.class);
        definition.setDestroyMethodName("close");
        registry.registerBeanDefinition(clazz.getName(), definition);
    }

}
项目:westcache    文件:WestCacheableClassPathScanner.java   
/**
 * Calls the parent search that will search and register all the candidates.
 * Then the registered objects are post processed to set them as
 * MapperFactoryBeans
 */
@Override
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
    Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);

    if (beanDefinitions.isEmpty()) {
        log.warn("No WestCacheable was found in '{}' package. " +
                        "Please check your configuration.",
                Arrays.toString(basePackages));
        return beanDefinitions;
    }

    for (val holder : beanDefinitions) {
        val definition = (GenericBeanDefinition) holder.getBeanDefinition();
        log.debug("Creating WestCacheableFactoryBean with name '{}' and '{}'",
                holder.getBeanName(), definition.getBeanClassName());

        // the mapper interface is the original class of the bean
        // but, the actual class of the bean is MapperFactoryBean
        definition.getPropertyValues().add("targetClass", definition.getBeanClassName());
        definition.setBeanClass(WestCacheableFactoryBean.class);
    }

    return beanDefinitions;
}
项目:spring4-understanding    文件:QualifierAnnotationTests.java   
@Test
public void testQualifiedByParentValue() {
    StaticApplicationContext parent = new StaticApplicationContext();
    GenericBeanDefinition parentLarry = new GenericBeanDefinition();
    parentLarry.setBeanClass(Person.class);
    parentLarry.getPropertyValues().add("name", "ParentLarry");
    parentLarry.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "parentLarry"));
    parent.registerBeanDefinition("someLarry", parentLarry);
    GenericBeanDefinition otherLarry = new GenericBeanDefinition();
    otherLarry.setBeanClass(Person.class);
    otherLarry.getPropertyValues().add("name", "OtherLarry");
    otherLarry.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "otherLarry"));
    parent.registerBeanDefinition("someOtherLarry", otherLarry);
    parent.refresh();

    StaticApplicationContext context = new StaticApplicationContext(parent);
    BeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
    reader.loadBeanDefinitions(CONFIG_LOCATION);
    context.registerSingleton("testBean", QualifiedByParentValueTestBean.class);
    context.refresh();
    QualifiedByParentValueTestBean testBean = (QualifiedByParentValueTestBean) context.getBean("testBean");
    Person person = testBean.getLarry();
    assertEquals("ParentLarry", person.getName());
}
项目:spring4-understanding    文件:GroovyBeanDefinitionWrapper.java   
protected AbstractBeanDefinition createBeanDefinition() {
    AbstractBeanDefinition bd = new GenericBeanDefinition();
    bd.setBeanClass(this.clazz);
    if (!CollectionUtils.isEmpty(this.constructorArgs)) {
        ConstructorArgumentValues cav = new ConstructorArgumentValues();
        for (Object constructorArg : this.constructorArgs) {
            cav.addGenericArgumentValue(constructorArg);
        }
        bd.setConstructorArgumentValues(cav);
    }
    if (this.parentName != null) {
        bd.setParentName(this.parentName);
    }
    this.definitionWrapper = new BeanWrapperImpl(bd);
    return bd;
}
项目:leopard    文件:OptionScanner.java   
@Override
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
    Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
    for (BeanDefinitionHolder holder : beanDefinitions) {
        GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();
        String id = getValue(definition);
        if (StringUtils.isEmpty(id)) {
            id = holder.getBeanName();
        }
        String className = holder.getBeanDefinition().getBeanClassName();
        // logger.info("holder:" + holder.getBeanName() + " className:" + className);
        OptionData.load(id, className);
        definition.getPropertyValues().add("innerClassName", definition.getBeanClassName());
        definition.setBeanClass(OptionFactoryBean.class);
    }
    return beanDefinitions;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:ConfigurationPropertiesBindingPostProcessorTests.java   
@Test
public void configurationPropertiesWithFactoryBean() throws Exception {
    ConfigurationPropertiesWithFactoryBean.factoryBeanInit = false;
    this.context = new AnnotationConfigApplicationContext() {
        @Override
        protected void onRefresh() throws BeansException {
            assertThat(ConfigurationPropertiesWithFactoryBean.factoryBeanInit)
                    .as("Init too early").isFalse();
            super.onRefresh();
        }
    };
    this.context.register(ConfigurationPropertiesWithFactoryBean.class);
    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setBeanClass(FactoryBeanTester.class);
    beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
    this.context.registerBeanDefinition("test", beanDefinition);
    this.context.refresh();
    assertThat(ConfigurationPropertiesWithFactoryBean.factoryBeanInit).as("No init")
            .isTrue();
}
项目:Dynamic-data-sources    文件:DynamicDataSourceRegister.java   
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
    // 将主数据源添加到更多数据源中
    targetDataSources.put("dataSource", defaultDataSource);
    DynamicDataSourceContextHolder.dataSourceIds.add("dataSource");
    // 添加更多数据源
    targetDataSources.putAll(customDataSources);
    for (String key : customDataSources.keySet()) {
        DynamicDataSourceContextHolder.dataSourceIds.add(key);
    }

    // 创建DynamicDataSource
    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setBeanClass(DynamicDataSource.class);
    beanDefinition.setSynthetic(true);
    MutablePropertyValues mpv = beanDefinition.getPropertyValues();
    mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
    mpv.addPropertyValue("targetDataSources", targetDataSources);
    registry.registerBeanDefinition("dataSource", beanDefinition);

    logger.info("Dynamic DataSource Registry");
}
项目:spring-content    文件:StoreUtils.java   
public static Set<GenericBeanDefinition> getStoreCandidates(ResourceLoader loader, String[] basePackages) {
    StoreCandidateComponentProvider scanner = new StoreCandidateComponentProvider(false);
    //scanner.setConsiderNestedRepositoryInterfaces(shouldConsiderNestedRepositories());
    scanner.setResourceLoader(loader);
    //scanner.setEnvironment(environment);

    /*for (TypeFilter filter : getExcludeFilters()) {
        scanner.addExcludeFilter(filter);
    }*/

    Set<GenericBeanDefinition> result = new HashSet<>();

    for (String basePackage : basePackages) {
        Set<BeanDefinition> candidates = scanner.findCandidateComponents(basePackage);
        for (BeanDefinition candidate : candidates)
            result.add((GenericBeanDefinition)candidate);
    }

    return result;  
}
项目:kekoa    文件:DynamicDataSourceRegister.java   
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
    // 将主数据源添加到更多数据源中
    targetDataSources.put("dataSource", defaultDataSource);
    DynamicDataSourceContextHolder.dataSourceIds.add("dataSource");
    // 添加更多数据源
    targetDataSources.putAll(customDataSources);
    for (String key : customDataSources.keySet()) {
        DynamicDataSourceContextHolder.dataSourceIds.add(key);
    }

    // 创建DynamicDataSource
    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setBeanClass(DynamicDataSource.class);
    beanDefinition.setSynthetic(true);
    MutablePropertyValues mpv = beanDefinition.getPropertyValues();
    mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
    mpv.addPropertyValue("targetDataSources", targetDataSources);
    registry.registerBeanDefinition("dataSource", beanDefinition);

    logger.info("Dynamic DataSource Registry");
}
项目:spring    文件:GroovyBeanDefinitionWrapper.java   
protected AbstractBeanDefinition createBeanDefinition() {
    AbstractBeanDefinition bd = new GenericBeanDefinition();
    bd.setBeanClass(this.clazz);
    if (!CollectionUtils.isEmpty(this.constructorArgs)) {
        ConstructorArgumentValues cav = new ConstructorArgumentValues();
        for (Object constructorArg : this.constructorArgs) {
            cav.addGenericArgumentValue(constructorArg);
        }
        bd.setConstructorArgumentValues(cav);
    }
    if (this.parentName != null) {
        bd.setParentName(this.parentName);
    }
    this.definitionWrapper = new BeanWrapperImpl(bd);
    return bd;
}
项目:tsharding    文件:DataSourceScanner.java   
/**
 * 将数据源注入到Spring中
 *
 * @param registry
 * @param dataSourcesMapping
 */
private void registerDataSources(BeanDefinitionRegistry registry,
                                 Map<String, Map<DataSourceType, DataSource>> dataSourcesMapping) {

    for (Map.Entry<String, Map<DataSourceType, DataSource>> entry : dataSourcesMapping.entrySet()) {
        final String name = entry.getKey();
        for (Map.Entry<DataSourceType, DataSource> subEntry : entry.getValue().entrySet()) {
            GenericBeanDefinition dataSourceBeanDefinition = new GenericBeanDefinition();
            dataSourceBeanDefinition.setBeanClass(DataSourceFactoryBean.class);
            ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues();
            constructorArgumentValues.addIndexedArgumentValue(0, subEntry.getValue());
            dataSourceBeanDefinition.setConstructorArgumentValues(constructorArgumentValues);
            String beanName = name + Character.toUpperCase(subEntry.getKey().name().charAt(0))
                    + subEntry.getKey().name().substring(1) + "DataSource";
            registry.registerBeanDefinition(beanName, dataSourceBeanDefinition);
        }
    }
}
项目:spring-boot-concourse    文件:ConfigurationPropertiesBindingPostProcessorTests.java   
@Test
public void configurationPropertiesWithFactoryBean() throws Exception {
    ConfigurationPropertiesWithFactoryBean.factoryBeanInit = false;
    this.context = new AnnotationConfigApplicationContext() {
        @Override
        protected void onRefresh() throws BeansException {
            assertThat(ConfigurationPropertiesWithFactoryBean.factoryBeanInit)
                    .as("Init too early").isFalse();
            super.onRefresh();
        }
    };
    this.context.register(ConfigurationPropertiesWithFactoryBean.class);
    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setBeanClass(FactoryBeanTester.class);
    beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
    this.context.registerBeanDefinition("test", beanDefinition);
    this.context.refresh();
    assertThat(ConfigurationPropertiesWithFactoryBean.factoryBeanInit).as("No init")
            .isTrue();
}
项目:indoqa-spring    文件:DynamicApplicationContextBuilder.java   
private static BeanDefinition createBeanDefinition(ComponentDefinition componentDefinition) {
    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();

    beanDefinition.setBeanClassName(componentDefinition.getComponentClass());
    beanDefinition.setScope(getScope(componentDefinition.getScope()));
    beanDefinition.setAutowireCandidate(true);
    beanDefinition.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_NAME);
    beanDefinition.setDependsOn(componentDefinition.getDependsOn());
    beanDefinition.setLazyInit(componentDefinition.isLazyInit());

    ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues();
    for (Object value : componentDefinition.getConstructorArguments()) {
        constructorArgumentValues.addIndexedArgumentValue(constructorArgumentValues.getArgumentCount(), value);
    }
    beanDefinition.setConstructorArgumentValues(constructorArgumentValues);

    MutablePropertyValues propertyValues = new MutablePropertyValues();
    for (PropertyValue propertyValue : componentDefinition.getPropertyValues()) {
        propertyValues.add(propertyValue.getName(), propertyValue.getValue());
    }
    beanDefinition.setPropertyValues(propertyValues);

    return beanDefinition;
}
项目:mybatis-spring-1.2.2    文件:MapperScanTest.java   
@Test
public void testScanWithExplicitSqlSessionTemplate() throws Exception {
  GenericBeanDefinition definition = new GenericBeanDefinition();
  definition.setBeanClass(SqlSessionTemplate.class);
  ConstructorArgumentValues constructorArgs = new ConstructorArgumentValues();
  constructorArgs.addGenericArgumentValue(new RuntimeBeanReference("sqlSessionFactory"));
  definition.setConstructorArgumentValues(constructorArgs);
  applicationContext.registerBeanDefinition("sqlSessionTemplate", definition);

  applicationContext.register(AppConfigWithSqlSessionTemplate.class);

  startContext();

  // all interfaces with methods should be loaded
  applicationContext.getBean("mapperInterface");
  applicationContext.getBean("mapperSubinterface");
  applicationContext.getBean("mapperChildInterface");
  applicationContext.getBean("annotatedMapper");

}
项目:mybatis-spring-1.2.2    文件:MapperScannerConfigurerTest.java   
@Before
public void setupContext() {
  applicationContext = new GenericApplicationContext();

  // add the mapper scanner as a bean definition rather than explicitly setting a
  // postProcessor on the context so initialization follows the same code path as reading from
  // an XML config file
  GenericBeanDefinition definition = new GenericBeanDefinition();
  definition.setBeanClass(MapperScannerConfigurer.class);
  definition.getPropertyValues().add("basePackage", "org.mybatis.spring.mapper");
  applicationContext.registerBeanDefinition("mapperScanner", definition);

  setupSqlSessionFactory("sqlSessionFactory");

  // assume support for autowiring fields is added by MapperScannerConfigurer via
  // org.springframework.context.annotation.ClassPathBeanDefinitionScanner.includeAnnotationConfig
}
项目:mybatis-spring-1.2.2    文件:MapperScannerConfigurerTest.java   
@Test
public void testNameGenerator() {
  GenericBeanDefinition definition = new GenericBeanDefinition();
  definition.setBeanClass(BeanNameGenerator.class);
  applicationContext.registerBeanDefinition("beanNameGenerator", definition);

  applicationContext.getBeanDefinition("mapperScanner").getPropertyValues().add(
      "nameGenerator", new RuntimeBeanReference("beanNameGenerator"));

  startContext();

  // only child inferfaces should be loaded and named with its class name
  applicationContext.getBean(MapperInterface.class.getName());
  applicationContext.getBean(MapperSubinterface.class.getName());
  applicationContext.getBean(MapperChildInterface.class.getName());
  applicationContext.getBean(AnnotatedMapper.class.getName());
}
项目:mybatis-spring-1.2.2    文件:MapperScannerConfigurerTest.java   
@Test
public void testScanWithExplicitSqlSessionFactoryViaPlaceholder() throws Exception {
  setupSqlSessionFactory("sqlSessionFactory2");

  // use a property placeholder for the session factory name
  applicationContext.getBeanDefinition("mapperScanner").getPropertyValues().add(
      "sqlSessionFactoryBeanName", "${sqlSessionFactoryBeanNameProperty}");

  Properties props = new java.util.Properties();
  props.put("sqlSessionFactoryBeanNameProperty", "sqlSessionFactory2");

  GenericBeanDefinition propertyDefinition = new GenericBeanDefinition();
  propertyDefinition.setBeanClass(PropertyPlaceholderConfigurer.class);
  propertyDefinition.getPropertyValues().add("properties", props);

  applicationContext.registerBeanDefinition("propertiesPlaceholder", propertyDefinition);

  testInterfaceScan();
}
项目:spring-data-keyvalue-redis    文件:RedisRepositoryConfigurationExtension.java   
@Override
protected AbstractBeanDefinition getDefaultKeyValueTemplateBeanDefinition(
        RepositoryConfigurationSource configurationSource) {

    RootBeanDefinition redisKeyValueAdapterDefinition = new RootBeanDefinition(RedisKeyValueAdapter.class);

    DirectFieldAccessor dfa = new DirectFieldAccessor(configurationSource);
    AnnotationAttributes aa = (AnnotationAttributes) dfa.getPropertyValue("attributes");

    GenericBeanDefinition indexConfiguration = new GenericBeanDefinition();
    indexConfiguration.setBeanClass(aa.getClass("indexConfiguration"));

    ConstructorArgumentValues constructorArgumentValuesForRedisKeyValueAdapter = new ConstructorArgumentValues();
    constructorArgumentValuesForRedisKeyValueAdapter.addGenericArgumentValue(indexConfiguration);
    redisKeyValueAdapterDefinition.setConstructorArgumentValues(constructorArgumentValuesForRedisKeyValueAdapter);

    RootBeanDefinition keyValueTemplateDefinition = new RootBeanDefinition(KeyValueTemplate.class);
    ConstructorArgumentValues constructorArgumentValuesForKeyValueTemplate = new ConstructorArgumentValues();
    constructorArgumentValuesForKeyValueTemplate.addGenericArgumentValue(redisKeyValueAdapterDefinition);
    keyValueTemplateDefinition.setConstructorArgumentValues(constructorArgumentValuesForKeyValueTemplate);

    return keyValueTemplateDefinition;
}
项目:contestparser    文件:ConfigurationPropertiesBindingPostProcessorTests.java   
@Test
public void configurationPropertiesWithFactoryBean() throws Exception {
    ConfigurationPropertiesWithFactoryBean.factoryBeanInit = false;
    this.context = new AnnotationConfigApplicationContext() {
        @Override
        protected void onRefresh() throws BeansException {
            assertFalse("Init too early",
                    ConfigurationPropertiesWithFactoryBean.factoryBeanInit);
            super.onRefresh();
        }
    };
    this.context.register(ConfigurationPropertiesWithFactoryBean.class);
    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setBeanClass(FactoryBeanTester.class);
    beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
    this.context.registerBeanDefinition("test", beanDefinition);
    this.context.refresh();
    assertTrue("No init", ConfigurationPropertiesWithFactoryBean.factoryBeanInit);
}
项目:spring-rest-client    文件:ClassPathSpringRestClientScanner.java   
/**
 * Calls the parent search that will search and register all the candidates.
 * Then the registered objects are post processed to set them as
 * MapperFactoryBeans
 */
@Override
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
    val beanDefinitions = super.doScan(basePackages);

    if (beanDefinitions.isEmpty()) {
        log.warn("No SpringRestClientEnabled was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
    } else {
        for (val holder : beanDefinitions) {
            val definition = (GenericBeanDefinition) holder.getBeanDefinition();

            if (log.isDebugEnabled()) {
                log.debug("Creating SpringRestClientFactoryBean with name '" + holder.getBeanName()
                        + "' and '" + definition.getBeanClassName() + "' interfaceClazz");
            }

            // the mapper interface is the original class of the bean
            // but, the actual class of the bean is MapperFactoryBean
            definition.getPropertyValues().add("interfaceClazz", definition.getBeanClassName());
            definition.setBeanClass(SpringRestClientFactoryBean.class);
        }
    }

    return beanDefinitions;
}
项目:diqube    文件:TestContextOverrideBean.java   
/**
 * Override a {@link BeanDefinition} in the given context, effectively replacing the bean that will be created.
 * 
 * This has to be called before the context is {@link GenericApplicationContext#refresh()}ed.
 * 
 * @param ctx
 *          The context to work on.
 * @param overriddenBeanClass
 *          Class of the bean that should be overridden.
 * @param newBeanClass
 *          Class of bean that should be used instead.
 */
public static void overrideBeanClass(GenericApplicationContext ctx, Class<?> overriddenBeanClass, Class<?> newBeanClass) {
  String overrideBeanDefName = null;
  for (String beanDefinitionName : ctx.getBeanFactory().getBeanDefinitionNames()) {
    if (ctx.getBeanFactory().getBeanDefinition(beanDefinitionName).getBeanClassName()
        .equals(overriddenBeanClass.getName())) {
      overrideBeanDefName = beanDefinitionName;
      break;
    }
  }

  GenericBeanDefinition overridingBeanDef =
      (GenericBeanDefinition) ((GenericBeanDefinition) ctx.getBeanFactory().getBeanDefinition(overrideBeanDefName))
          .cloneBeanDefinition();
  overridingBeanDef.setBeanClass(newBeanClass);
  ctx.registerBeanDefinition(overrideBeanDefName, overridingBeanDef);
}
项目:resteasy-spring-boot    文件:ResteasyEmbeddedServletInitializer.java   
/**
 * Creates a Servlet bean definition for the given JAX-RS application
 *
 * @param applicationClass
 * @param path
 * @return a Servlet bean definition for the given JAX-RS application
 */
private GenericBeanDefinition createApplicationServlet(Class<? extends Application> applicationClass, String path) {
    GenericBeanDefinition applicationServletBean = new GenericBeanDefinition();
    applicationServletBean.setFactoryBeanName(ResteasyApplicationBuilder.BEAN_NAME);
    applicationServletBean.setFactoryMethodName("build");

    Set<Class<?>> resources = allResources;

    ConstructorArgumentValues values = new ConstructorArgumentValues();
    values.addIndexedArgumentValue(0, applicationClass.getName());
    values.addIndexedArgumentValue(1, path);
    values.addIndexedArgumentValue(2, resources);
    values.addIndexedArgumentValue(3, providers);
    applicationServletBean.setConstructorArgumentValues(values);

    applicationServletBean.setAutowireCandidate(false);
    applicationServletBean.setScope("singleton");

    return applicationServletBean;
}
项目:darks-orm    文件:MapperClassDefinitionScanner.java   
@Override
protected Set<BeanDefinitionHolder> doScan(String... scanPackages)
{
    Set<BeanDefinitionHolder> definitions = super.doScan(scanPackages);
    if (definitions.isEmpty())
    {
        log.warn("No bean definition found in target packages " + Arrays.toString(scanPackages));
    }
    else
    {
        for (BeanDefinitionHolder holder : definitions)
        {
            GenericBeanDefinition definition = (GenericBeanDefinition) holder
                    .getBeanDefinition();
            processBeanDefinition(definition);
        }
    }
    return definitions;
}
项目:zxl    文件:MulCommonBaseServiceParser.java   
private BeanDefinition buildSessionFactoryBeanDefinition(Element element, String name, BeanDefinitionParserDelegate beanDefinitionParserDelegate, BeanDefinitionRegistry beanDefinitionRegistry) {
    AbstractBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setAttribute(ID_ATTRIBUTE, name + SESSION_FACTORY_SUFFIX);
    beanDefinition.setBeanClass(LocalSessionFactoryBean.class);
    beanDefinition.setParentName(SESSION_FACTORY_PARENT_BEAN_NAME);
    MutablePropertyValues propertyValues = new MutablePropertyValues();
    propertyValues.add("dataSource", new RuntimeBeanReference(name + DATA_SOURCE_SUFFIX));
    if (element.hasAttribute(TABLE_PREFIX_NAME) && !StringUtil.isEmpty(element.getAttribute(TABLE_PREFIX_NAME))) {
        AbstractBeanDefinition namingStrategyBeanDefinition = new GenericBeanDefinition();
        String randomBeanName = UUID.randomUUID().toString();
        namingStrategyBeanDefinition.setAttribute(ID_ATTRIBUTE, randomBeanName);
        namingStrategyBeanDefinition.setBeanClass(HibernateNamingStrategy.class);
        MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
        mutablePropertyValues.add("prefix", element.getAttribute(TABLE_PREFIX_NAME));
        namingStrategyBeanDefinition.setPropertyValues(mutablePropertyValues);
        beanDefinitionRegistry.registerBeanDefinition(randomBeanName, namingStrategyBeanDefinition);
        propertyValues.addPropertyValue("namingStrategy", new RuntimeBeanReference(randomBeanName));
    }
    beanDefinition.setPropertyValues(propertyValues);
    beanDefinitionParserDelegate.parsePropertyElements(element, beanDefinition);
    return beanDefinition;
}
项目:spring-boot-capgemini    文件:SettingBackedBeanFactoryPostProcessor.java   
private BeanDefinition createBeanDefinition(Object settings, Object setting, String factoryBeanName, Method factoryMethod) {
    final GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setFactoryBeanName(factoryBeanName);
    definition.setFactoryMethodName(factoryMethod.getName());

    //Create method arguments (confusingly called constructor arguments in spring)
    final ConstructorArgumentValues arguments = new ConstructorArgumentValues();
    arguments.addIndexedArgumentValue(0, setting);

    final int parameterCount = factoryMethod.getParameterTypes().length;
    if (parameterCount == 2) {
        arguments.addIndexedArgumentValue(1, settings);
    } else if (parameterCount > 2) {
        throw getExceptionFactory().createInvalidArgumentsException(factoryMethod);
    }

    //TODO more checking of method arguments to ensure they're correct

    definition.setConstructorArgumentValues(arguments);

    return definition;
}
项目:mybatis-spring    文件:MapperScanTest.java   
@Test
public void testScanWithExplicitSqlSessionTemplate() throws Exception {
  GenericBeanDefinition definition = new GenericBeanDefinition();
  definition.setBeanClass(SqlSessionTemplate.class);
  ConstructorArgumentValues constructorArgs = new ConstructorArgumentValues();
  constructorArgs.addGenericArgumentValue(new RuntimeBeanReference("sqlSessionFactory"));
  definition.setConstructorArgumentValues(constructorArgs);
  applicationContext.registerBeanDefinition("sqlSessionTemplate", definition);

  applicationContext.register(AppConfigWithSqlSessionTemplate.class);

  startContext();

  // all interfaces with methods should be loaded
  applicationContext.getBean("mapperInterface");
  applicationContext.getBean("mapperSubinterface");
  applicationContext.getBean("mapperChildInterface");
  applicationContext.getBean("annotatedMapper");

}
项目:mybatis-spring    文件:MapperScannerConfigurerTest.java   
@Before
public void setupContext() {
  applicationContext = new GenericApplicationContext();

  // add the mapper scanner as a bean definition rather than explicitly setting a
  // postProcessor on the context so initialization follows the same code path as reading from
  // an XML config file
  GenericBeanDefinition definition = new GenericBeanDefinition();
  definition.setBeanClass(MapperScannerConfigurer.class);
  definition.getPropertyValues().add("basePackage", "org.mybatis.spring.mapper");
  applicationContext.registerBeanDefinition("mapperScanner", definition);

  setupSqlSessionFactory("sqlSessionFactory");

  // assume support for autowiring fields is added by MapperScannerConfigurer via
  // org.springframework.context.annotation.ClassPathBeanDefinitionScanner.includeAnnotationConfig
}
项目:mybatis-spring    文件:MapperScannerConfigurerTest.java   
@Test
public void testNameGenerator() {
  GenericBeanDefinition definition = new GenericBeanDefinition();
  definition.setBeanClass(BeanNameGenerator.class);
  applicationContext.registerBeanDefinition("beanNameGenerator", definition);

  applicationContext.getBeanDefinition("mapperScanner").getPropertyValues().add(
      "nameGenerator", new RuntimeBeanReference("beanNameGenerator"));

  startContext();

  // only child inferfaces should be loaded and named with its class name
  applicationContext.getBean(MapperInterface.class.getName());
  applicationContext.getBean(MapperSubinterface.class.getName());
  applicationContext.getBean(MapperChildInterface.class.getName());
  applicationContext.getBean(AnnotatedMapper.class.getName());
}
项目:mybatis-spring    文件:MapperScannerConfigurerTest.java   
@Test
public void testScanWithExplicitSqlSessionFactoryViaPlaceholder() throws Exception {
  setupSqlSessionFactory("sqlSessionFactory2");

  // use a property placeholder for the session factory name
  applicationContext.getBeanDefinition("mapperScanner").getPropertyValues().add(
      "sqlSessionFactoryBeanName", "${sqlSessionFactoryBeanNameProperty}");

  Properties props = new java.util.Properties();
  props.put("sqlSessionFactoryBeanNameProperty", "sqlSessionFactory2");

  GenericBeanDefinition propertyDefinition = new GenericBeanDefinition();
  propertyDefinition.setBeanClass(PropertyPlaceholderConfigurer.class);
  propertyDefinition.getPropertyValues().add("properties", props);

  applicationContext.registerBeanDefinition("propertiesPlaceholder", propertyDefinition);

  testInterfaceScan();
}
项目:refreshable-beans    文件:SpringContextWrapper.java   
private void createAndRegisterBean(BeanDefinitionRegistry registry,
        String beanName,  Class<?>[] interfaces, ResourceScriptSource rs,
        long refreshCheckDelay) {
    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setFactoryBeanName(DEFAULT_SCRIPT_FACTORY_NAME + beanName);
    beanDefinition.setFactoryMethodName(DEFAULT_SCRIPT_FACTORY_METHOD_NAME);
    beanDefinition.getConstructorArgumentValues().clear();
    beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, rs);
    beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(1, interfaces);
    beanDefinition.setAutowireCandidate(true);
    beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE);
    beanDefinition.setAttribute(
            ScriptFactoryPostProcessor.REFRESH_CHECK_DELAY_ATTRIBUTE, refreshCheckDelay);       
    registry.registerBeanDefinition(beanName,beanDefinition);       

}
项目:geomajas-project-server    文件:BeanDefinitionDtoConverterServiceImpl.java   
/**
 * Convert from a DTO to an internal Spring bean definition.
 * 
 * @param beanDefinitionDto The DTO object.
 * @return Returns a Spring bean definition.
 */
public BeanDefinition toInternal(BeanDefinitionInfo beanDefinitionInfo) {
    if (beanDefinitionInfo instanceof GenericBeanDefinitionInfo) {
        GenericBeanDefinitionInfo genericInfo = (GenericBeanDefinitionInfo) beanDefinitionInfo;
        GenericBeanDefinition def = new GenericBeanDefinition();
        def.setBeanClassName(genericInfo.getClassName());
        if (genericInfo.getPropertyValues() != null) {
            MutablePropertyValues propertyValues = new MutablePropertyValues();
            for (Entry<String, BeanMetadataElementInfo> entry : genericInfo.getPropertyValues().entrySet()) {
                BeanMetadataElementInfo info = entry.getValue();
                propertyValues.add(entry.getKey(), toInternal(info));
            }
            def.setPropertyValues(propertyValues);
        }
        return def;
    } else if (beanDefinitionInfo instanceof ObjectBeanDefinitionInfo) {
        ObjectBeanDefinitionInfo objectInfo = (ObjectBeanDefinitionInfo) beanDefinitionInfo;
        return createBeanDefinitionByIntrospection(objectInfo.getObject());
    } else {
        throw new IllegalArgumentException("Conversion to internal of " + beanDefinitionInfo.getClass().getName()
                + " not implemented");
    }
}
项目:geomajas-project-server    文件:BeanDefinitionDtoConverterServiceImpl.java   
/**
 * Convert from an internal Spring bean definition to a DTO.
 * 
 * @param beanDefinition The internal Spring bean definition.
 * @return Returns a DTO representation.
 */
public BeanDefinitionInfo toDto(BeanDefinition beanDefinition) {
    if (beanDefinition instanceof GenericBeanDefinition) {
        GenericBeanDefinitionInfo info = new GenericBeanDefinitionInfo();
        info.setClassName(beanDefinition.getBeanClassName());

        if (beanDefinition.getPropertyValues() != null) {
            Map<String, BeanMetadataElementInfo> propertyValues = new HashMap<String, BeanMetadataElementInfo>();
            for (PropertyValue value : beanDefinition.getPropertyValues().getPropertyValueList()) {
                Object obj = value.getValue();
                if (obj instanceof BeanMetadataElement) {
                    propertyValues.put(value.getName(), toDto((BeanMetadataElement) obj));
                } else {
                    throw new IllegalArgumentException("Type " + obj.getClass().getName()
                            + " is not a BeanMetadataElement for property: " + value.getName());
                }
            }
            info.setPropertyValues(propertyValues);
        }
        return info;
    } else {
        throw new IllegalArgumentException("Conversion to DTO of " + beanDefinition.getClass().getName()
                + " not implemented");
    }
}
项目:geomajas-project-server    文件:BeanDefinitionDtoConverterServiceImpl.java   
private BeanDefinition createBeanDefinitionByIntrospection(Object object, NamedBeanMap refs,
        ConversionService conversionService) {
    validate(object);
    GenericBeanDefinition def = new GenericBeanDefinition();
    def.setBeanClass(object.getClass());
    MutablePropertyValues propertyValues = new MutablePropertyValues();
    for (PropertyDescriptor descriptor : BeanUtils.getPropertyDescriptors(object.getClass())) {
        if (descriptor.getWriteMethod() != null) {
            try {
                Object value = descriptor.getReadMethod().invoke(object, (Object[]) null);
                if (value != null) {
                    if ("id".equals(descriptor.getName())) {

                    } else {
                        propertyValues.addPropertyValue(descriptor.getName(),
                                createMetadataElementByIntrospection(value, refs, conversionService));
                    }
                }
            } catch (Exception e) {
                // our contract says to ignore this property
            }
        }
    }
    def.setPropertyValues(propertyValues);
    return def;
}
项目:geomajas-project-server    文件:BaseBeanFactory.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<BeanDefinitionHolder> createBeans(Map<String, Object> parameters) throws RuntimeConfigException {
    GenericBeanDefinition def = new GenericBeanDefinition();
    def.setBeanClassName(className);
    MutablePropertyValues propertyValues = new MutablePropertyValues();
    List<NamedObject> namedObjects = new ArrayList<NamedObject>();
    if (checkCollection(BEAN_REFS, NamedObject.class, parameters) != Priority.NONE) {
        namedObjects.addAll((Collection) parameters.get(BEAN_REFS));
    }
    for (String name : parameters.keySet()) {
        if (!ignoredParams.contains(name)) {
            propertyValues.addPropertyValue(name, beanDefinitionDtoConverterService
                    .createBeanMetadataElementByIntrospection(parameters.get(name), namedObjects));
        }
    }
    def.setPropertyValues(propertyValues);
    BeanDefinitionHolder holder = new BeanDefinitionHolder(def, (String) parameters.get(BEAN_NAME));
    List<BeanDefinitionHolder> holders = new ArrayList<BeanDefinitionHolder>();
    holders.add(holder);
    return holders;
}