SpringBoot通过yml等配置文件动态生成多个Bean
package test.config;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
import java.util.Map;
import java.util.Objects;
/**
* @author wenei
* @date 2022-01-06 20:00
*/
@Configuration
@EnableConfigurationProperties(BeanProperties.class)
@Import(AppConfig.ImportConfig.class)
public class AppConfig {
public static class ImportConfig implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private BeanProperties beanProperties;
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
for (Map.Entry<String, String> entry : beanProperties.getMapping().entrySet()) {
// 注册bean
RootBeanDefinition beanDefinition = new RootBeanDefinition();
beanDefinition.setBeanClass(Config.class);
MutablePropertyValues values = new MutablePropertyValues();
values.addPropertyValue("value", entry.getValue());
beanDefinition.setPropertyValues(values);
beanDefinitionRegistry.registerBeanDefinition(entry.getKey(), beanDefinition);
}
}
@Override
public void setEnvironment(Environment environment) {
// 通过Binder将environment中的值转成对象
beanProperties = Binder.get(environment).bind(getPropertiesPrefix(BeanProperties.class), BeanProperties.class).get();
}
private String getPropertiesPrefix(Class<?> tClass) {
return Objects.requireNonNull(AnnotationUtils.getAnnotation(tClass, ConfigurationProperties.class)).prefix();
}
}
}