Example usage for org.springframework.beans.factory.support DefaultListableBeanFactory getBeanNamesForType

List of usage examples for org.springframework.beans.factory.support DefaultListableBeanFactory getBeanNamesForType

Introduction

In this page you can find the example usage for org.springframework.beans.factory.support DefaultListableBeanFactory getBeanNamesForType.

Prototype

@Override
    public String[] getBeanNamesForType(@Nullable Class<?> type) 

Source Link

Usage

From source file:org.spring.guice.module.SpringModule.java

public SpringModule(DefaultListableBeanFactory beanFactory) {
    this.beanFactory = beanFactory;
    if (beanFactory.getBeanNamesForType(GuiceModuleMetadata.class).length > 0) {
        this.matcher = new CompositeTypeMatcher(beanFactory.getBeansOfType(GuiceModuleMetadata.class).values());
    }/*  w w w  .  j a  v  a2 s  .co m*/
}

From source file:com.wavemaker.runtime.data.cloudfoundry.CloudFoundryDataServiceBeanFactoryPostProcessor.java

/**
 * @param beanFactory//from  w w  w . j  av a2 s  .c  o m
 */
private void processHibernateProperties(DefaultListableBeanFactory beanFactory) {
    String[] sessionFactoryBeanNames = beanFactory
            .getBeanNamesForType(ConfigurationAndSessionFactoryBean.class);

    for (String sfBean : sessionFactoryBeanNames) {
        BeanDefinition beanDefinition = getBeanDefinition(beanFactory, sfBean);
        if (sfBean.contains(DataServiceConstants.AUX_BEAN_SUFFIX)) {
            beanDefinition.setLazyInit(false);
        } else {
            beanDefinition.setLazyInit(true);
        }
        MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
        PropertyValue hibernateProperties = propertyValues.getPropertyValue("hibernateProperties");

        ManagedProperties hibernatePropsPropertyValue = null;
        if (hibernateProperties != null) {
            Object value = hibernateProperties.getValue();
            if (value instanceof ManagedProperties) {
                hibernatePropsPropertyValue = (ManagedProperties) hibernateProperties.getValue();
                TypedStringValue dialect = (TypedStringValue) hibernatePropsPropertyValue
                        .get(new TypedStringValue(DataServiceConstants.HIBERNATE_DIALECT_PROPERTY));
                if (dialect != null && dialect
                        .equals(new TypedStringValue("com.wavemaker.runtime.data.dialect.MySQLDialect"))) {
                    hibernatePropsPropertyValue.put(
                            new TypedStringValue(DataServiceConstants.HIBERNATE_DIALECT_PROPERTY),
                            new TypedStringValue("org.hibernate.dialect.MySQLDialect"));
                }
            }
        } else {
            hibernatePropsPropertyValue = new ManagedProperties();
        }
    }
}

From source file:com.wavemaker.runtime.data.cloudfoundry.CloudFoundryDataServiceBeanFactoryPostProcessor.java

/**
 * @param defaultListableBeanFactory/*from   w w w.  j a  v  a 2s .c o  m*/
 */
private void processDataSources(DefaultListableBeanFactory defaultListableBeanFactory) {
    String[] dataSourceBeanNames = defaultListableBeanFactory.getBeanNamesForType(DataSource.class);

    if (dataSourceBeanNames.length <= 1) {
        // When there is only 1 DataSource, the provided auto-staging should be sufficient
        return;
    }

    for (String dsBean : dataSourceBeanNames) {
        if (!dsBean.endsWith(DS_BEAN_SUFFIX)) {
            continue;
        }

        String serviceName = dsBean.substring(0, dsBean.indexOf(DS_BEAN_SUFFIX));

        if (!serviceExists(serviceName)) {
            boolean foundAlias = false;
            for (String alias : defaultListableBeanFactory.getAliases(dsBean)) {
                if (serviceExists(alias)) {
                    serviceName = alias;
                    foundAlias = true;
                    break;
                }
            }
            if (!foundAlias) {
                log.warn("Expected to find a service with the name '" + serviceName + "' but none was found.");
                continue;
            }
        }

        RdbmsServiceInfo service = this.cloudEnvironment.getServiceInfo(serviceName, RdbmsServiceInfo.class);
        if (service != null) {
            defaultListableBeanFactory.removeBeanDefinition(dsBean);
            DataSource cfDataSource = new RdbmsServiceCreator().createService(service);
            defaultListableBeanFactory.registerSingleton(dsBean, cfDataSource);
        } else {
            log.warn("Service " + serviceName + " exists, but is not an RDBMS service as expected.");
        }
    }
}

From source file:org.jnap.core.persistence.factory.DaoFactoryBkp.java

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
    Assert.isAssignable(DefaultListableBeanFactory.class, registry.getClass(),
            "The DaoFactory only works within a DefaultListableBeanFactory capable"
                    + "BeanFactory, your BeanDefinitionRegistry is " + registry.getClass());
    final DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) registry;

    // Initialize all SessionFactory beans
    String[] factoryNames = beanFactory.getBeanNamesForType(EntityManagerFactory.class);
    Set<EntityManagerFactory> factories = new HashSet<EntityManagerFactory>(factoryNames.length);
    for (String factoryName : factoryNames) {
        factories.add(beanFactory.getBean(factoryName, EntityManagerFactory.class));
    }/*from w ww . j a va2 s .c  o  m*/

    for (EntityManagerFactory factory : factories) {
        factory.getMetamodel().getEntities();
        for (EntityType<?> entityMetadata : factory.getMetamodel().getEntities()) {
            Class<? extends PersistentModel> entityClass = (Class<? extends PersistentModel>) entityMetadata
                    .getJavaType();
            if (entityClass != null && !isDaoDefinedForEntity(beanFactory, entityClass)) {
                String daoName = buildDaoName(entityClass);
                beanFactory.registerBeanDefinition(daoName, createDaoDefinition(entityClass, factory));
                daoNameCache.put(entityClass, daoName);
            }
        }
    }

    factories.clear();
    factories = null;
}

From source file:io.gravitee.gateway.services.apikeyscache.ApiKeysCacheService.java

@Override
protected void doStart() throws Exception {
    if (enabled) {
        super.doStart();

        LOGGER.info("Overriding API key repository implementation with cached API Key repository");
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext
                .getParent()).getBeanFactory();

        this.apiKeyRepository = beanFactory.getBean(ApiKeyRepository.class);
        LOGGER.debug("Current API key repository implementation is {}", apiKeyRepository.getClass().getName());

        String[] beanNames = beanFactory.getBeanNamesForType(ApiKeyRepository.class);
        String oldBeanName = beanNames[0];

        beanFactory.destroySingleton(oldBeanName);

        LOGGER.debug("Register API key repository implementation {}", ApiKeyRepositoryWrapper.class.getName());
        beanFactory.registerSingleton(ApiKeyRepository.class.getName(),
                new ApiKeyRepositoryWrapper(this.apiKeyRepository, cache));

        eventManager.subscribeForEvents(this, ReactorEvent.class);

        executorService = Executors.newScheduledThreadPool(threads, new ThreadFactory() {
            private int counter = 0;
            private String prefix = "apikeys-refresher";

            @Override/*from   w w  w.  j av a  2  s .  c o m*/
            public Thread newThread(Runnable r) {
                return new Thread(r, prefix + '-' + counter++);
            }
        });
    }
}

From source file:com.google.enterprise.connector.db.MockDBConnectorFactory.java

/**
 * Creates a database connector./* ww w  .  j a  v a 2 s.c  o m*/
 *
 * @param config map of configuration values.
 */
/* TODO(jlacey): Extract the Spring instantiation code in CM. */
@Override
public Connector makeConnector(Map<String, String> config) throws RepositoryException {
    // TODO(jlacey): The placeholder values are in the EPPC bean in
    // connectorDefaults.xml, but we're not loading that, and doing so
    // would unravel a ball of string: using setLocation instead of
    // setProperties (since the EPPC bean already has properties),
    // which in turn requires the ByteArrayResource machinery in
    // InstanceInfo or writing the properties to a file.
    Properties props = new Properties();
    for (String configKey : DBConnectorType.CONFIG_KEYS) {
        props.put(configKey, "");
    }
    // Escape MyBatis syntax that looks like a Spring placeholder.
    // See https://jira.springsource.org/browse/SPR-4953
    props.put("docIds", "#{'$'}{docIds}");
    props.putAll(config);

    Resource prototype = new ClassPathResource("config/connectorInstance.xml", MockDBConnectorFactory.class);
    Resource defaults = new ClassPathResource("config/connectorDefaults.xml", MockDBConnectorFactory.class);

    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader beanReader = new XmlBeanDefinitionReader(factory);
    try {
        beanReader.loadBeanDefinitions(prototype);
        beanReader.loadBeanDefinitions(defaults);
    } catch (BeansException e) {
        throw new RepositoryException(e);
    }

    PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
    cfg.setProperties(props);
    cfg.postProcessBeanFactory(factory);

    String[] beanList = factory.getBeanNamesForType(DiffingConnector.class);
    Assert.assertEquals(Arrays.asList(beanList).toString(), 1, beanList.length);
    return (Connector) factory.getBean(beanList[0]);
}

From source file:com.google.enterprise.connector.filesystem.ConfigTest.java

public void testInstantiation() {
    Properties props = new Properties();
    props.putAll(goodConfig);//from w  w w. ja  va  2 s. c  o  m
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
    // Refer to InstanceInfo.makeConnectorWithSpring
    //(com.google.enterprise.connector.instantiator) for more info on how
    // these files are loaded to instantiate connector.
    reader.loadBeanDefinitions(new ClassPathResource(DEFAULTS_CONFIG_FILE, ConfigTest.class));
    reader.loadBeanDefinitions(new ClassPathResource(INSTANCE_CONFIG_FILE, ConfigTest.class));
    PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
    cfg.setProperties(props);
    cfg.postProcessBeanFactory(beanFactory);
    String[] beans = beanFactory.getBeanNamesForType(Connector.class);
    assertEquals(1, beans.length);
    Object obj = beanFactory.getBean(beans[0]);
    assertTrue("Expecting instance of Connector interface but the actual " + "instance: "
            + obj.getClass().toString(), obj instanceof Connector);
}

From source file:org.springframework.beans.factory.DefaultListableBeanFactoryTests.java

@Test
public void testGetBeanWithArgsNotCreatedForFactoryBeanChecking() {
    DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
    RootBeanDefinition bd1 = new RootBeanDefinition(ConstructorDependency.class);
    bd1.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
    lbf.registerBeanDefinition("bd1", bd1);
    RootBeanDefinition bd2 = new RootBeanDefinition(ConstructorDependencyFactoryBean.class);
    bd2.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
    lbf.registerBeanDefinition("bd2", bd2);

    ConstructorDependency bean = lbf.getBean(ConstructorDependency.class, 42);
    assertThat(bean.beanName, equalTo("bd1"));
    assertThat(bean.spouseAge, equalTo(42));

    assertEquals(1, lbf.getBeanNamesForType(ConstructorDependency.class).length);
    assertEquals(1, lbf.getBeanNamesForType(ConstructorDependencyFactoryBean.class).length);
    assertEquals(1, lbf//from  ww  w .  ja va 2  s.com
            .getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, Object.class)).length);
    assertEquals(0, lbf
            .getBeanNamesForType(ResolvableType.forClassWithGenerics(FactoryBean.class, String.class)).length);
}

From source file:org.springframework.beans.factory.DefaultListableBeanFactoryTests.java

/**
 * @param singleton whether the bean created from the factory method on
 * the bean instance should be a singleton or prototype. This flag is
 * used to allow checking of the new ability in 1.2.4 to determine the type
 * of a prototype created from invoking a factory method on a bean instance
 * in the factory./*from ww w .  j  a va2 s . c  o m*/
 */
private void findTypeOfPrototypeFactoryMethodOnBeanInstance(boolean singleton) {
    String expectedNameFromProperties = "tony";
    String expectedNameFromArgs = "gordon";

    DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
    RootBeanDefinition instanceFactoryDefinition = new RootBeanDefinition(BeanWithFactoryMethod.class);
    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.add("name", expectedNameFromProperties);
    instanceFactoryDefinition.setPropertyValues(pvs);
    lbf.registerBeanDefinition("factoryBeanInstance", instanceFactoryDefinition);

    RootBeanDefinition factoryMethodDefinitionWithProperties = new RootBeanDefinition();
    factoryMethodDefinitionWithProperties.setFactoryBeanName("factoryBeanInstance");
    factoryMethodDefinitionWithProperties.setFactoryMethodName("create");
    if (!singleton) {
        factoryMethodDefinitionWithProperties.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
    }
    lbf.registerBeanDefinition("fmWithProperties", factoryMethodDefinitionWithProperties);

    RootBeanDefinition factoryMethodDefinitionGeneric = new RootBeanDefinition();
    factoryMethodDefinitionGeneric.setFactoryBeanName("factoryBeanInstance");
    factoryMethodDefinitionGeneric.setFactoryMethodName("createGeneric");
    if (!singleton) {
        factoryMethodDefinitionGeneric.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
    }
    lbf.registerBeanDefinition("fmGeneric", factoryMethodDefinitionGeneric);

    RootBeanDefinition factoryMethodDefinitionWithArgs = new RootBeanDefinition();
    factoryMethodDefinitionWithArgs.setFactoryBeanName("factoryBeanInstance");
    factoryMethodDefinitionWithArgs.setFactoryMethodName("createWithArgs");
    ConstructorArgumentValues cvals = new ConstructorArgumentValues();
    cvals.addGenericArgumentValue(expectedNameFromArgs);
    factoryMethodDefinitionWithArgs.setConstructorArgumentValues(cvals);
    if (!singleton) {
        factoryMethodDefinitionWithArgs.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
    }
    lbf.registerBeanDefinition("fmWithArgs", factoryMethodDefinitionWithArgs);

    assertEquals(4, lbf.getBeanDefinitionCount());
    List<String> tbNames = Arrays.asList(lbf.getBeanNamesForType(TestBean.class));
    assertTrue(tbNames.contains("fmWithProperties"));
    assertTrue(tbNames.contains("fmWithArgs"));
    assertEquals(2, tbNames.size());

    TestBean tb = (TestBean) lbf.getBean("fmWithProperties");
    TestBean second = (TestBean) lbf.getBean("fmWithProperties");
    if (singleton) {
        assertSame(tb, second);
    } else {
        assertNotSame(tb, second);
    }
    assertEquals(expectedNameFromProperties, tb.getName());

    tb = (TestBean) lbf.getBean("fmGeneric");
    second = (TestBean) lbf.getBean("fmGeneric");
    if (singleton) {
        assertSame(tb, second);
    } else {
        assertNotSame(tb, second);
    }
    assertEquals(expectedNameFromProperties, tb.getName());

    TestBean tb2 = (TestBean) lbf.getBean("fmWithArgs");
    second = (TestBean) lbf.getBean("fmWithArgs");
    if (singleton) {
        assertSame(tb2, second);
    } else {
        assertNotSame(tb2, second);
    }
    assertEquals(expectedNameFromArgs, tb2.getName());
}