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
在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 提供了多种读取配置文件方式,以下是其中几种常用的方式: 1. application.properties/application.yml:在 src/main/resources 目录下创建 application.properties 或 application.yml 文件,可以在其中设置应用程序的配置信息,例如: ``` server.port=8080 spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 ``` 2. @Value 注解:在代码中使用 @Value 注解读取配置信息,例如: ``` @Value("${server.port}") private int serverPort; @Value("${spring.datasource.url}") private String dataSourceUrl; @Value("${spring.datasource.username}") private String dataSourceUsername; @Value("${spring.datasource.password}") private String dataSourcePassword; ``` 3. @ConfigurationProperties 注解:通过 @ConfigurationProperties 注解将配置文件中的属性值注入到 Bean 中,例如: ``` @ConfigurationProperties(prefix = "spring.datasource") public class DataSourceProperties { private String url; private String username; private String password; // getter/setter } ``` 4. Environment 接口:通过 Environment 接口读取配置信息,例如: ``` @Autowired private Environment env; int serverPort = env.getProperty("server.port", Integer.class); String dataSourceUrl = env.getProperty("spring.datasource.url"); String dataSourceUsername = env.getProperty("spring.datasource.username"); String dataSourcePassword = env.getProperty("spring.datasource.password"); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值