SpringBoot自定义配置注入的方式:自定义配置文件注入,从mysql读取配置进行注入

本文涉及的产品
云数据库 RDS MySQL,集群版 2核4GB 100GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: SpringBoot自定义配置注入的方式:自定义配置文件注入,从mysql读取配置进行注入

创建配置注入测试类

@Configuration
@ConfigurationProperties(prefix = ConfigTestPre.PREFIX)
@Data
public class ConfigTestPre {
   
   

    public static final String PREFIX = "hx.config";

    @Value("${hx.config:}") // 会优先使用prefix的方式注入
    private String test = "1";

    private String cfg;

}

1、自定义配置文件的注入

public class CustomerConfigInject  implements EnvironmentPostProcessor {
   
   
    PropertiesPropertySourceLoader load=new PropertiesPropertySourceLoader();

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
   
   
        MutablePropertySources propertySources = environment.getPropertySources();
        Resource resource=new ClassPathResource("custom.properties"); 
        PropertySource propertySource; 
        try {
   
   
            propertySource = load.load("customProperties",resource).get(0);
            propertySources.addFirst(propertySource);
        } catch (IOException e){
   
   
            e.printStackTrace();
        }

    }
}

META-INF/spring.factories中指定配置类:

org.springframework.boot.env.EnvironmentPostProcessor=com.hx.temp.config.CustomerConfigInject

在resource文件夹中添加自己的配置文件 custom.properties

hx.config=123

2、从数据库查询配置进行注入

数据库sql

DROP TABLE IF EXISTS `setting_table`;
CREATE TABLE `setting_table`  (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' ',
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `value` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

INSERT INTO `whx`.`setting_table`(`id`, `name`, `value`) VALUES (1, 'hx.config.test', 'fromMysql-test');
INSERT INTO `whx`.`setting_table`(`id`, `name`, `value`) VALUES (2, 'hx.config.cfg', 'fromMysql-cfg');

查询数据库配置,手动绑定配置到指定配置类中

项目启动执行一次,后面可以调接口刷新配置

package com.hx.config.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.*;

/**
 * @ClassName ConfigSupportConfiguration
 * @Description //TODO
 * @Author WHX
 * @Date 2022/6/5 15:00
 **/
@Component
@Slf4j
public class ConfigSupportConfiguration {
   
   
    public  static final String SQL = "select id, name, value from setting_table";
    private static final String SOURCE_NAME = ConfigSupportConfiguration.class.getSimpleName();

    @Value("${hx.config.load_sql:" + SQL + "}")
    private final String settings_sql = SQL;
    @Autowired
    private ConfigurableEnvironment environment;
    @Autowired
    private DataSource dataSource;

    @Autowired
    private ConfigTestPre configTestPre;

    @PostConstruct
    public Object refreshMysqlInjectConfig() {
   
   
        // 从数据库查询配置
        final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        final List<Map<String, Object>> rows = jdbcTemplate.queryForList(settings_sql);

        // 获取或者创建 PropertySource
        MapPropertySource propertySource = Optional.ofNullable((MapPropertySource) environment.getPropertySources().get(SOURCE_NAME))
                .orElse(new MapPropertySource(SOURCE_NAME, new HashMap<>()));

        Map<String, Object> source = propertySource.getSource();
        Map<String, Object> updateSource = new HashMap<>();

        for (final Map<String, Object> row : rows) {
   
   
            String name = String.valueOf(row.get("name"));
            String value = String.valueOf(row.get("value"));
            if (!StringUtils.hasText(name) || value == null) {
   
   
                continue;
            }
            Object property = source.get(name);
            if (null != property && property.equals(value)) {
   
   
                // 配置未发生改变
                continue;
            }
            source.put(name, value);
            updateSource.put(name, value);
        }

        if (updateSource.isEmpty()) return "{}";
        environment.getPropertySources().addLast(propertySource);
        // 配置注入早已经执行过了,所以这里手动去执行配置绑定到指定类(prefix的方式绑定)
        // 注意:这个仅针对configTestPre一个类进行了手动配置注入,并不是刷新所有的配置类;
        Binder.get(environment).bind(configTestPre.PREFIX, Bindable.ofInstance(configTestPre));
        return updateSource;
    }
}

刷新配置

定义刷新配置的接口

@RestController
@RequestMapping("/config/refresh")
public class RefreshConfigController {
   
   
    @Autowired
    private ConfigSupportConfiguration configSupportConfiguration;

    @GetMapping("/mysqlInject")
    public Object refreshMysqlInjectConfig(){
   
   
        return configSupportConfiguration.refreshMysqlInjectConfig();
    }
}

修改数据库后,调用刷新接口:

curl localhost:80/config/refresh/mysqlInject
在这里插入图片描述

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
5天前
|
Java 应用服务中间件 开发者
Java面试题:解释Spring Boot的优势及其自动配置原理
Java面试题:解释Spring Boot的优势及其自动配置原理
28 0
|
3天前
|
运维 关系型数据库 MySQL
【实操记录】MySQL主从配置
本文使用MySQL原生支持的主从同步机制,详细记录了配置步骤及运维操作方法,可供大家直接参考、使用。 本文假设已经部署了两台主机的MySQL软件,且数据库服务正常,详细部署步骤可本站搜索:"mysql二进制安装包部署"
10 0
|
10天前
|
Java
no main manifest attribute,软件开发部署SpringBoot要填配置,不填配置,报错哦@_@
no main manifest attribute,软件开发部署SpringBoot要填配置,不填配置,报错哦@_@
|
12天前
|
XML Java 关系型数据库
Action:Consider the following: If you want an embedde ,springBoot配置数据库,补全springBoot的xml和mysql配置信息就好了
Action:Consider the following: If you want an embedde ,springBoot配置数据库,补全springBoot的xml和mysql配置信息就好了
|
12天前
|
SQL 关系型数据库 MySQL
【MySQL】主从异步复制配置
【MySQL】主从异步复制配置
16 1
|
12天前
|
Java 测试技术 Spring
支付系统15-----支付宝支付,引入支付参数,如何使支付宝的配置信息变成SpringBoot相关的配置信息
支付系统15-----支付宝支付,引入支付参数,如何使支付宝的配置信息变成SpringBoot相关的配置信息
|
12天前
|
Java 数据库连接 mybatis
SpringBoot配置Mybatis注意事项,mappers层下的name命名空间,要落实到Dao的video类,resultType要落到bean,配置好mybatis的对应依赖。
SpringBoot配置Mybatis注意事项,mappers层下的name命名空间,要落实到Dao的video类,resultType要落到bean,配置好mybatis的对应依赖。
|
3天前
|
网络协议 关系型数据库 MySQL
MySQL PXC集群配置IPv6
前阵子为PXC集群配置IPv6支持,遇见奇怪的问题,就是SST同步时总是报错,为此在官网论坛提交了问题,未得到答案,最后偶然得到了答案
11 0
|
10天前
|
SQL NoSQL 关系型数据库
若依修改02,若以提供了多种版本,RuoYi-Cloud和SpringBoot+Vue都是PC端的,如果想要适配手机端,用Uniapp+vue,导入Mysql和启动Redis
若依修改02,若以提供了多种版本,RuoYi-Cloud和SpringBoot+Vue都是PC端的,如果想要适配手机端,用Uniapp+vue,导入Mysql和启动Redis
|
存储 前端开发 Java
SpringBoot文件上传和下载
SpringBoot文件上传和下载
SpringBoot文件上传和下载