SpringBoot从数据库加载配置信息

Spring Boot 通过@Value注解可实现获取配置文件中的数据,而配置文件中的数据可以通过修改MutablePropertySources从数据库注入
该示例基于Hibernate实现

更多精彩

实体类

  1. 根据Hibernate的配置,实体类对应数据库中的表即可
@Entity
@Table(name = "sys_config")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Config implements Serializable {

    @Id
    private Long id;

    @Column
    private String code;

    @Column
    private String value;

    @Column
    private String name;

    @Column
    private String description;

  ...
}

服务类

  1. 服务类用于从数据库中获取列表信息
@Service
public class SystemConfigService extends SimpleHibernateService<Config, Long> {
   ...
}

配置类

  1. 该配置类会在系统启动时自动加载
  2. 根据内部逻辑会将从数据库取出的列表信息注入到MutablePropertySources属性集合中
  3. 动态注入的属性集合无需有对应的 .properties 文件存在
@Configuration
public class SystemConfig {

    @Autowired
    private ConfigurableEnvironment environment;

    @Autowired
    private SystemConfigService service;

    @PostConstruct
    public void initDatabasePropertySourceUsage() {
        // 获取系统属性集合
        MutablePropertySources propertySources = environment.getPropertySources();

        try {
            // 从数据库获取自定义变量列表
            Map<String, String> collect = service.getAll().stream().collect(Collectors.toMap(Config::getCode, Config::getValue));

            // 将转换后的列表加入属性中
            Properties properties = new Properties();
            properties.putAll(collect);

            // 将属性转换为属性集合,并指定名称
            PropertiesPropertySource constants = new PropertiesPropertySource("system-config", properties);

            // 定义寻找属性的正则,该正则为系统默认属性集合的前缀
            Pattern p = Pattern.compile("^applicationConfig.*");

            // 接收系统默认属性集合的名称
            String name = null;
            // 标识是否找到系统默认属性集合
            boolean flag = false;

            // 遍历属性集合
            for (PropertySource<?> source : propertySources) {
                // 正则匹配
                if (p.matcher(source.getName()).matches()) {
                    // 接收名称
                    name = source.getName();
                    // 变更标识
                    flag = true;

                    break;
                }
            }

            if (flag) {
                // 找到则将自定义属性添加到该属性之前
                propertySources.addBefore(name, constants);
            } else {
                // 没找到默认添加到第一位
                propertySources.addFirst(constants);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

工具类

  1. 由于Spring Boot不支持静态变量的自动注入,所以需要使用一个非静态的setter方法将通过@Value注解获取到的属性信息赋值给对应静态变量
  2. @DependsOn({"systemConfig"}) 的意思是说 Constants 依赖于 SystemConfig ,所以需要确保 SystemConfig 在 Constants 之前加载
@Configuration
@DependsOn({"systemConfig"})
public class Constants {

    // 资源服务器地址
    public static String RESOURCE_SERVER_URL;

    @Value("${resource.server.url}")
    public void setResourceServerUrl(String resourceServerUrl) {
        RESOURCE_SERVER_URL = resourceServerUrl;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,974评论 6 342
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,600评论 1 92
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,001评论 19 139
  • 入门 介绍 Spring Boot Spring Boot 使您可以轻松地创建独立的、生产级的基于 Spring ...
    Hsinwong阅读 16,960评论 2 89
  • 窗外的风没有停歇的吹着,我的心也开始不平静,一个原本过去的简单的问题却被重提而更加复杂。 对于朋友我一直以真心对待...
    H杰娜h阅读 279评论 0 0