Java Code Examples for org.springframework.beans.factory.config.ConfigurableListableBeanFactory#getBeanDefinitionNames()

The following examples show how to use org.springframework.beans.factory.config.ConfigurableListableBeanFactory#getBeanDefinitionNames() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ParentBeanFactoryPostProcessor.java    From jdal with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void postProcessBeanFactory(
		ConfigurableListableBeanFactory beanFactory) throws BeansException {
	
	String[] names = beanFactory.getBeanDefinitionNames();
	
	for (String beanName : names) {
		Parent parent = beanFactory.findAnnotationOnBean(beanName, Parent.class);
		
		if (parent != null) {
			BeanDefinition bd = beanFactory.getBeanDefinition(beanName);
			bd.setParentName(parent.value());
		}
	}
}
 
Example 2
Source File: UifBeanFactoryPostProcessor.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Iterates through all beans in the factory and invokes processing
 *
 * @param beanFactory bean factory instance to process
 * @throws org.springframework.beans.BeansException
 */
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    Set<String> processedBeanNames = new HashSet<String>();

    LOG.info("Beginning post processing of bean factory for UIF expressions");

    String[] beanNames = beanFactory.getBeanDefinitionNames();
    for (int i = 0; i < beanNames.length; i++) {
        String beanName = beanNames[i];
        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

        processBeanDefinition(beanName, beanDefinition, beanFactory, processedBeanNames);
    }

    LOG.info("Finished post processing of bean factory for UIF expressions");
}
 
Example 3
Source File: KotlinLambdaToFunctionAutoConfiguration.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
/**
 * Will transform all discovered Kotlin's Function lambdas to java
 * Supplier, Function and Consumer, retaining the original Kotlin type
 * characteristics.
 *
 * @return the bean factory post processor
 */
@Bean
public BeanFactoryPostProcessor kotlinToFunctionTransformer() {
	return new BeanFactoryPostProcessor() {

		@Override
		public void postProcessBeanFactory(
				ConfigurableListableBeanFactory beanFactory) throws BeansException {

			String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
			for (String beanDefinitionName : beanDefinitionNames) {
				BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDefinitionName);

				ResolvableType rt = beanDefinition.getResolvableType();
				if (rt.getType().getTypeName().startsWith("kotlin.jvm.functions.Function")) {
					RootBeanDefinition cbd = new RootBeanDefinition(KotlinFunctionWrapper.class);
					ConstructorArgumentValues ca = new ConstructorArgumentValues();
					ca.addGenericArgumentValue(beanDefinition);
					cbd.setConstructorArgumentValues(ca);
					((BeanDefinitionRegistry) beanFactory).registerBeanDefinition(beanDefinitionName + FunctionRegistration.REGISTRATION_NAME_SUFFIX, cbd);
				}
			}
		}
	};
}
 
Example 4
Source File: SpringCloudConfiguration.java    From ByteJTA with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

		String[] beanNameArray = beanFactory.getBeanDefinitionNames();
		for (int i = 0; i < beanNameArray.length; i++) {
			BeanDefinition beanDef = beanFactory.getBeanDefinition(beanNameArray[i]);
			String beanClassName = beanDef.getBeanClassName();

			if (FEIGN_FACTORY_CLASS.equals(beanClassName) == false) {
				continue;
			}

			MutablePropertyValues mpv = beanDef.getPropertyValues();
			PropertyValue pv = mpv.getPropertyValue("name");
			String client = String.valueOf(pv.getValue() == null ? "" : pv.getValue());
			if (StringUtils.isNotBlank(client)) {
				this.transientClientSet.add(client);
			}

		}

		this.fireAfterPropertiesSet();

	}
 
Example 5
Source File: SpringCloudSecondaryConfiguration.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

		String[] beanNameArray = beanFactory.getBeanDefinitionNames();
		for (int i = 0; i < beanNameArray.length; i++) {
			BeanDefinition beanDef = beanFactory.getBeanDefinition(beanNameArray[i]);
			String beanClassName = beanDef.getBeanClassName();

			if (FEIGN_FACTORY_CLASS.equals(beanClassName) == false) {
				continue;
			}

			MutablePropertyValues mpv = beanDef.getPropertyValues();
			PropertyValue pv = mpv.getPropertyValue("name");
			String client = String.valueOf(pv.getValue() == null ? "" : pv.getValue());
			if (StringUtils.isNotBlank(client)) {
				this.transientClientSet.add(client);
			}

		}

		this.fireAfterPropertiesSet();

	}
 
Example 6
Source File: SpringCloudConfiguration.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

		String[] beanNameArray = beanFactory.getBeanDefinitionNames();
		for (int i = 0; i < beanNameArray.length; i++) {
			BeanDefinition beanDef = beanFactory.getBeanDefinition(beanNameArray[i]);
			String beanClassName = beanDef.getBeanClassName();

			if (FEIGN_FACTORY_CLASS.equals(beanClassName) == false) {
				continue;
			}

			MutablePropertyValues mpv = beanDef.getPropertyValues();
			PropertyValue pv = mpv.getPropertyValue("name");
			String client = String.valueOf(pv.getValue() == null ? "" : pv.getValue());
			if (StringUtils.isNotBlank(client)) {
				this.transientClientSet.add(client);
			}

		}

		this.fireAfterPropertiesSet();

	}
 
Example 7
Source File: CustomScopeAnnotationConfigurer.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory clbf) throws BeansException {
	for (String beanName : clbf.getBeanDefinitionNames()) {
		BeanDefinition definition = clbf.getBeanDefinition(beanName);
		registerJsfCdiToSpring(definition);
	}
}
 
Example 8
Source File: AutoJsonRpcServiceImplExporter.java    From jsonrpc4j with MIT License 5 votes vote down vote up
/**
 * Finds the beans to expose.
 * <p>
 * Searches parent factories as well.
 */
private static Map<String, String> findServiceBeanDefinitions(ConfigurableListableBeanFactory beanFactory) {
	final Map<String, String> serviceBeanNames = new HashMap<>();
	
	for (String beanName : beanFactory.getBeanDefinitionNames()) {
		AutoJsonRpcServiceImpl autoJsonRpcServiceImplAnnotation = beanFactory.findAnnotationOnBean(beanName, AutoJsonRpcServiceImpl.class);
		JsonRpcService jsonRpcServiceAnnotation = beanFactory.findAnnotationOnBean(beanName, JsonRpcService.class);
		
		if (null != autoJsonRpcServiceImplAnnotation) {
			
			if (null == jsonRpcServiceAnnotation) {
				throw new IllegalStateException("on the bean [" + beanName + "], @" +
						AutoJsonRpcServiceImpl.class.getSimpleName() + " was found, but not @" +
						JsonRpcService.class.getSimpleName() + " -- both are required");
			}
			
			List<String> paths = new ArrayList<>();
			Collections.addAll(paths, autoJsonRpcServiceImplAnnotation.additionalPaths());
			paths.add(jsonRpcServiceAnnotation.value());
			
			for (String path : paths) {
				if (!PATTERN_JSONRPC_PATH.matcher(path).matches()) {
					throw new RuntimeException("the path [" + path + "] for the bean [" + beanName + "] is not valid");
				}
				
				logger.info("exporting bean [{}] ---> [{}]", beanName, path);
				if (isNotDuplicateService(serviceBeanNames, beanName, path)) {
                       serviceBeanNames.put(path, beanName);
                   }
			}
			
		}
	}
	
	collectFromParentBeans(beanFactory, serviceBeanNames);
	return serviceBeanNames;
}
 
Example 9
Source File: AutoJsonRpcServiceExporter.java    From jsonrpc4j with MIT License 5 votes vote down vote up
/**
 * Finds the beans to expose
 * map.
 * <p>
 * Searches parent factories as well.
 */
private static Map<String, String> findServiceBeanDefinitions(ConfigurableListableBeanFactory beanFactory) {
	final Map<String, String> serviceBeanNames = new HashMap<>();
	for (String beanName : beanFactory.getBeanDefinitionNames()) {
		JsonRpcService jsonRpcPath = beanFactory.findAnnotationOnBean(beanName, JsonRpcService.class);
		if (hasServiceAnnotation(jsonRpcPath)) {
			String pathValue = jsonRpcPath.value();
			logger.debug("Found JSON-RPC path '{}' for bean [{}].", pathValue, beanName);
			if (isNotDuplicateService(serviceBeanNames, beanName, pathValue))
				serviceBeanNames.put(pathValue, beanName);
		}
	}
	collectFromParentBeans(beanFactory, serviceBeanNames);
	return serviceBeanNames;
}
 
Example 10
Source File: RefreshScopeConfig.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
	for (String beanName : factory.getBeanDefinitionNames()) {
		BeanDefinition beanDef = factory.getBeanDefinition(beanName);
		if (beanDef.getBeanClassName() != null && beanDef.getBeanClassName().startsWith("com.tmobile.pacman")
				&& !beanDef.getBeanClassName().startsWith("com.tmobile.pacman.api.notification.config.PacmanQuartzConfiguration")) {
			beanDef.setScope("refresh");
		}
	}
}
 
Example 11
Source File: RefreshScopeConfig.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
        throws BeansException {
    for (String beanName : factory.getBeanDefinitionNames()) {
        BeanDefinition beanDef = factory.getBeanDefinition(beanName);
        if (beanDef.getBeanClassName() != null
                && beanDef.getBeanClassName().startsWith(
                        "com.tmobile.pacman")) {
            beanDef.setScope("refresh");
        }
    }
}
 
Example 12
Source File: FileSystemBeanFactoryPostProcessor.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
    String[] names = factory.getBeanDefinitionNames();
    for (String name : names) {
        BeanDefinition def = factory.getBeanDefinition(name);
        visitor.visitBeanDefinition(def);
    }
}
 
Example 13
Source File: ExtensionsAdminController.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * hmmm, does not work yet, how to get a list with all overwritten beans like the output from to the log.info
 * http://www.docjar.com/html/api/org/springframework/beans/factory/support/DefaultListableBeanFactory.java.html
 * 
 * @return
 */
private List getOverwrittenBeans() {
    final ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(CoreSpringFactory.servletContext);
    final XmlWebApplicationContext context = (XmlWebApplicationContext) applicationContext;
    final ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    final String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
    for (int i = 0; i < beanDefinitionNames.length; i++) {
        final String beanName = beanDefinitionNames[i];
        if (!beanName.contains("#")) {
            final BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
            // System.out.println(beanDef.getOriginatingBeanDefinition());
        }
    }
    return null;
}
 
Example 14
Source File: MyBeanFactoryPostProcessor.java    From code with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    System.out.println("MyBeanFactoryPostProcessor...postProcessBeanFactory...");
    int count = beanFactory.getBeanDefinitionCount();
    String[] names = beanFactory.getBeanDefinitionNames();
    System.out.println("当前BeanFactory中有" + count + " 个Bean");
    System.out.println(Arrays.asList(names));
}
 
Example 15
Source File: ExtensionsAdminController.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * hmmm, does not work yet, how to get a list with all overwritten beans like the output from to the log.info
 * http://www.docjar.com/html/api/org/springframework/beans/factory/support/DefaultListableBeanFactory.java.html
 * 
 * @return
 */
private List getOverwrittenBeans() {
    final ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(CoreSpringFactory.servletContext);
    final XmlWebApplicationContext context = (XmlWebApplicationContext) applicationContext;
    final ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    final String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
    for (int i = 0; i < beanDefinitionNames.length; i++) {
        final String beanName = beanDefinitionNames[i];
        if (!beanName.contains("#")) {
            final BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
            // System.out.println(beanDef.getOriginatingBeanDefinition());
        }
    }
    return null;
}
 
Example 16
Source File: LiveBeansView.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Actually generate a JSON snapshot of the beans in the given ApplicationContexts.
 * <p>This implementation doesn't use any JSON parsing libraries in order to avoid
 * third-party library dependencies. It produces an array of context description
 * objects, each containing a context and parent attribute as well as a beans
 * attribute with nested bean description objects. Each bean object contains a
 * bean, scope, type and resource attribute, as well as a dependencies attribute
 * with a nested array of bean names that the present bean depends on.
 * @param contexts the set of ApplicationContexts
 * @return the JSON document
 */
protected String generateJson(Set<ConfigurableApplicationContext> contexts) {
	StringBuilder result = new StringBuilder("[\n");
	for (Iterator<ConfigurableApplicationContext> it = contexts.iterator(); it.hasNext();) {
		ConfigurableApplicationContext context = it.next();
		result.append("{\n\"context\": \"").append(context.getId()).append("\",\n");
		if (context.getParent() != null) {
			result.append("\"parent\": \"").append(context.getParent().getId()).append("\",\n");
		}
		else {
			result.append("\"parent\": null,\n");
		}
		result.append("\"beans\": [\n");
		ConfigurableListableBeanFactory bf = context.getBeanFactory();
		String[] beanNames = bf.getBeanDefinitionNames();
		boolean elementAppended = false;
		for (String beanName : beanNames) {
			BeanDefinition bd = bf.getBeanDefinition(beanName);
			if (isBeanEligible(beanName, bd, bf)) {
				if (elementAppended) {
					result.append(",\n");
				}
				result.append("{\n\"bean\": \"").append(beanName).append("\",\n");
				result.append("\"aliases\": ");
				appendArray(result, bf.getAliases(beanName));
				result.append(",\n");
				String scope = bd.getScope();
				if (!StringUtils.hasText(scope)) {
					scope = BeanDefinition.SCOPE_SINGLETON;
				}
				result.append("\"scope\": \"").append(scope).append("\",\n");
				Class<?> beanType = bf.getType(beanName);
				if (beanType != null) {
					result.append("\"type\": \"").append(beanType.getName()).append("\",\n");
				}
				else {
					result.append("\"type\": null,\n");
				}
				result.append("\"resource\": \"").append(getEscapedResourceDescription(bd)).append("\",\n");
				result.append("\"dependencies\": ");
				appendArray(result, bf.getDependenciesForBean(beanName));
				result.append("\n}");
				elementAppended = true;
			}
		}
		result.append("]\n");
		result.append("}");
		if (it.hasNext()) {
			result.append(",\n");
		}
	}
	result.append("]");
	return result.toString();
}
 
Example 17
Source File: BusWiringBeanFactoryPostProcessor.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) {
    Object inject = bus;
    if (inject == null) {
        inject = getBusForName(Bus.DEFAULT_BUS_ID, factory, true, null);
    } else {
        if (!factory.containsBeanDefinition(Bus.DEFAULT_BUS_ID)
            && !factory.containsSingleton(Bus.DEFAULT_BUS_ID)) {
            factory.registerSingleton(Bus.DEFAULT_BUS_ID, bus);
        }
    }
    for (String beanName : factory.getBeanDefinitionNames()) {
        BeanDefinition beanDefinition = factory.getBeanDefinition(beanName);
        BusWiringType type
            = (BusWiringType)beanDefinition.getAttribute(AbstractBeanDefinitionParser.WIRE_BUS_ATTRIBUTE);
        if (type == null) {
            continue;
        }
        String busname = (String)beanDefinition.getAttribute(AbstractBeanDefinitionParser.WIRE_BUS_NAME);
        String create = (String)beanDefinition
            .getAttribute(AbstractBeanDefinitionParser.WIRE_BUS_CREATE);
        Object inj = inject;
        if (busname != null) {
            if (bus != null) {
                continue;
            }
            inj = getBusForName(busname, factory, create != null, create);
        }
        beanDefinition.removeAttribute(AbstractBeanDefinitionParser.WIRE_BUS_NAME);
        beanDefinition.removeAttribute(AbstractBeanDefinitionParser.WIRE_BUS_ATTRIBUTE);
        beanDefinition.removeAttribute(AbstractBeanDefinitionParser.WIRE_BUS_CREATE);
        if (create == null) {
            if (BusWiringType.PROPERTY == type) {
                beanDefinition.getPropertyValues()
                    .addPropertyValue("bus", inj);
            } else if (BusWiringType.CONSTRUCTOR == type) {
                ConstructorArgumentValues constructorArgs = beanDefinition.getConstructorArgumentValues();
                insertConstructorArg(constructorArgs, inj);
            }
        }
    }
}
 
Example 18
Source File: BaseAutoConfiguration.java    From graphql-spqr-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
private <T> T findQualifiedBeanByType(Class<? extends T> type, String qualifierValue, Class<? extends Annotation> qualifierType) {
    final NoSuchBeanDefinitionException noSuchBeanDefinitionException = new NoSuchBeanDefinitionException(qualifierValue, "No matching " + type.getSimpleName() +
            " bean found for qualifier " + qualifierValue + " of type " + qualifierType.getSimpleName() + " !");
    try {

        if (StringUtils.isEmpty(qualifierValue)) {
            if (qualifierType.equals(Qualifier.class)) {
                return Optional.of(
                        context.getBean(type))
                        .orElseThrow(() -> noSuchBeanDefinitionException);
            }
            return context.getBean(
                    Arrays.stream(context.getBeanNamesForAnnotation(qualifierType))
                            .filter(beanName -> type.isInstance(context.getBean(beanName)))
                            .findFirst()
                            .orElseThrow(() -> noSuchBeanDefinitionException),
                    type);
        }

        return BeanFactoryAnnotationUtils.qualifiedBeanOfType(context.getBeanFactory(), type, qualifierValue);
    } catch (NoSuchBeanDefinitionException noBeanException) {
        ConfigurableListableBeanFactory factory = context.getBeanFactory();

        for (String name : factory.getBeanDefinitionNames()) {
            BeanDefinition bd = factory.getBeanDefinition(name);

            if (bd.getSource() instanceof StandardMethodMetadata) {
                StandardMethodMetadata metadata = (StandardMethodMetadata) bd.getSource();

                if (metadata.getReturnTypeName().equals(type.getName())) {
                    Map<String, Object> attributes = metadata.getAnnotationAttributes(qualifierType.getName());
                    if (null != attributes) {
                        if (qualifierType.equals(Qualifier.class)) {
                            if (qualifierValue.equals(attributes.get("value"))) {
                                return context.getBean(name, type);
                            }
                        }
                        return context.getBean(name, type);
                    }
                }
            }
        }

        throw noSuchBeanDefinitionException;
    }
}
 
Example 19
Source File: BaseAutoConfiguration.java    From graphql-spqr-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"unchecked"})
private List<SpqrBean> findGraphQLApiBeans() {
    ConfigurableListableBeanFactory factory = context.getBeanFactory();

    List<SpqrBean> spqrBeans = new ArrayList<>();

    for (String beanName : factory.getBeanDefinitionNames()) {
        BeanDefinition bd = factory.getBeanDefinition(beanName);

        if (bd.getSource() instanceof StandardMethodMetadata) {
            StandardMethodMetadata metadata = (StandardMethodMetadata) bd.getSource();

            Map<String, Object> attributes = metadata.getAnnotationAttributes(GraphQLApi.class.getName());
            if (null == attributes) {
                continue;
            }

            SpqrBean spqrBean = new SpqrBean(context, beanName, metadata.getIntrospectedMethod().getAnnotatedReturnType());

            Map<String, Object> withResolverBuildersAttributes = metadata.getAnnotationAttributes(WithResolverBuilders.class.getTypeName());
            if (withResolverBuildersAttributes != null) {
                AnnotationAttributes[] annotationAttributesArray = (AnnotationAttributes[]) withResolverBuildersAttributes.get("value");
                Arrays.stream(annotationAttributesArray)
                        .forEach(annotationAttributes ->
                                spqrBean.getResolverBuilders().add(
                                        new ResolverBuilderBeanIdentity(
                                                (Class<? extends ResolverBuilder>) annotationAttributes.get("value"),
                                                (String) annotationAttributes.get("qualifierValue"),
                                                (Class<? extends Annotation>) annotationAttributes.get("qualifierType"))
                                )
                        );
            } else {
                Map<String, Object> withResolverBuilderAttributes = metadata.getAnnotationAttributes(WithResolverBuilder.class.getTypeName());
                if (withResolverBuilderAttributes != null) {
                    spqrBean.getResolverBuilders().add(
                            new ResolverBuilderBeanIdentity(
                                    (Class<? extends ResolverBuilder>) withResolverBuilderAttributes.get("value"),
                                    (String) withResolverBuilderAttributes.get("qualifierValue"),
                                    (Class<? extends Annotation>) withResolverBuilderAttributes.get("qualifierType"))
                    );
                }
            }

            spqrBeans.add(spqrBean);
        }
    }

    return spqrBeans;
}
 
Example 20
Source File: BeanUtils.java    From spring-context-support with Apache License 2.0 4 votes vote down vote up
/**
 * Get Bean names from {@link ConfigurableListableBeanFactory} by type
 *
 * @param beanFactory {@link ConfigurableListableBeanFactory}
 * @param beanType    The  {@link Class type} of Bean
 * @return the array of bean names.
 */
protected static Set<String> doGetBeanNames(ConfigurableListableBeanFactory beanFactory, Class<?> beanType) {

    String[] allBeanNames = beanFactory.getBeanDefinitionNames();

    Set<String> beanNames = new LinkedHashSet<String>();

    for (String beanName : allBeanNames) {

        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

        Class<?> beanClass = resolveBeanType(beanFactory, beanDefinition);

        if (beanClass != null && ClassUtils.isAssignable(beanType, beanClass)) {

            beanNames.add(beanName);

        }

    }

    return Collections.unmodifiableSet(beanNames);

}