All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.javaclub.configcenter.spring.utils.BeanRegistrationUtil Maven / Gradle / Ivy

The newest version!
package com.github.javaclub.configcenter.spring.utils;

import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;


public class BeanRegistrationUtil {

	public static boolean registerBeanDefinitionIfNotExists(BeanDefinitionRegistry registry, String beanName,
			Class beanClass) {
		return registerBeanDefinitionIfNotExists(registry, beanName, beanClass, null);
	}

	public static boolean registerBeanDefinitionIfNotExists(BeanDefinitionRegistry registry, String beanName,
			Class beanClass, Map extraPropertyValues) {
		if (registry.containsBeanDefinition(beanName)) {
			return false;
		}

		String[] candidates = registry.getBeanDefinitionNames();

		for (String candidate : candidates) {
			BeanDefinition beanDefinition = registry.getBeanDefinition(candidate);
			if (Objects.equals(beanDefinition.getBeanClassName(), beanClass.getName())) {
				return false;
			}
		}

		BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(beanClass).getBeanDefinition();

		if (extraPropertyValues != null) {
			for (Map.Entry entry : extraPropertyValues.entrySet()) {
				beanDefinition.getPropertyValues().add(entry.getKey(), entry.getValue());
			}
		}

		registry.registerBeanDefinition(beanName, beanDefinition);

		return true;
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy