SpringBoot通过yml等配置文件动态生成多个Bean

12 篇文章 1 订阅

demo说明

通过在yaml等配置文件中配置map,然后根据map生成多个Bean。

比如如下配置:就应该生成2个Bean。

最后效果:应该在Spring容器中生成name=key1, name=key2的两个Bean。
在这里插入图片描述

配置文件对应的类

package test.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author wenei
 * @date 2022-01-06 20:00
 */
@ConfigurationProperties("test")
@Data
public class BeanProperties {

    private Map<String, String> mapping;
}

Config

注入到Spring容器中的Bean类型。

package test.config;

import lombok.Data;

/**
 * @author wenei
 * @date 2022-01-06 20:00
 */
@Data
public class Config {

    private String value;
}

核心处理类

通过@Import导入ImportBeanDefinitionRegistrar的实现类;

同时实现EnvironmentAware接口,注入Environment,然后通过Binder将Environment配置绑定出一个配置类;

最后通过配置类动态绑定BeanDefinition到容器中。

(为什么不能使用Autowired方式注入BeanProperties?我的理解:因为这还只是Spring容器的加入BeanDefinition的阶段,所有的BeanDefinition还没有实例化成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();
        }
    }
}

最后使用

package test.api;

import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import test.config.BeanProperties;
import test.config.Config;

import javax.annotation.Resource;

/**
 * @author wenei
 * @date 2022-01-06 20:02
 */
@RestController
@RequiredArgsConstructor
public class ConfigApi {

    private final BeanProperties beanProperties;

    @Resource(name = "key1")
    private Config key1Config;

    @GetMapping("/config")
    public String config() {
        return beanProperties.getMapping().toString();
    }

    @GetMapping("key1")
    public String key1() {
        return key1Config.getValue();
    }
}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Spring Boot 中,你可以通过使用 `@PropertySource` 注解来引入多个 YAML 配置文件,并将它们的属性值加载到应用程序中。 首先,在你的 Spring Boot 应用程序的主类上,添加 `@PropertySource` 注解,并指定要引入的配置文件路径。如下所示: ```java @SpringBootApplication @PropertySources({ @PropertySource("classpath:config1.yml"), @PropertySource("classpath:config2.yml") }) public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } ``` 在上面的示例中,我们使用了 `@PropertySources` 注解来指定多个配置文件的路径,每个配置文件都通过 `@PropertySource` 注解来指定。你可以根据需要添加更多的 `@PropertySource` 注解来引入更多的配置文件。 然后,在你的配置文件中,可以使用 `@ConfigurationProperties` 注解来绑定配置文件中的属性值到对应的 Java 对象中。如下所示: ```java @Configuration @ConfigurationProperties(prefix = "your.prefix") public class YourConfiguration { private String property1; private String property2; // ... // getter and setter methods } ``` 在上面的示例中,我们使用了 `@ConfigurationProperties` 注解来将配置文件中以 `your.prefix` 为前缀的属性值绑定到对应的 Java 对象中。其中,`your.prefix.property1` 对应于配置文件中的属性名。 通过这种方式,你可以在 Spring Boot 应用程序中引入多个 YAML 配置文件,并将它们的属性值加载到应用程序中使用。请确保你的 YAML 配置文件的格式正确,并且在类路径下可访问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥牛火锅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值