spring启动之前自定义属性源,并将其添加到Environment(无感更新)

1,spring启动之前的处理
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {


    /**
     * 自定义配置源
     */
    private static final String PROPERTY_SOURCE_NAME = "databaseProperties";

    /**
     * 从数据库读取配置加载到 environment
     */
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        System.out.println("DbPropertiesPostProcessor.postProcessEnvironment");
        Map propertySource = new HashMap<>();
        try {
            String enabled = environment.getProperty("spring.datasource.druid.filter.config.enabled");
            String datasourcePassword = environment.getProperty("spring.datasource.druid.master.password");
            if (Boolean.parseBoolean(enabled)) {
                String connectProperties = environment.getProperty("spring.datasource.druid.connectProperties");
                String decryptionKey = connectProperties.split("config.decrypt.key=")[1];
               // 解密 datasourcePassword = ConfigTools.decrypt(decryptionKey, datasourcePassword);
            }  
            // 手动将数据源构建到ServiceConfig
            DataSource ds = DataSourceBuilder
                    .create()
                    .username(environment.getProperty("spring.datasource.druid.master.username"))
                    .password(datasourcePassword)
                    .url(environment.getProperty("spring.datasource.druid.master.url"))
                    .driverClassName("com.mysql.cj.jdbc.Driver")
                    .build();

            // 获取所有属性
            Connection connection = ds.getConnection();
            System.out.println("ReadDbPropertiesPostProcessor configuracion from database");
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM sys_config");
            ResultSet rs = preparedStatement.executeQuery();
            // 将所有的配置添加到自定义源中
            while (rs.next()) {
                propertySource.put(rs.getString("config_key"), rs.getString("config_value"));
            }
            rs.close();
            preparedStatement.clearParameters();
            preparedStatement.close();
            connection.close();

            // 创建具有最高优先级的自定义属性源,并将其添加到Spring Environment
            environment.getPropertySources().addFirst(new MapPropertySource(PROPERTY_SOURCE_NAME, propertySource));
        } catch (Throwable e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

2,resources/META-INF的spring.factories下加注册
org.springframework.boot.env.EnvironmentPostProcessor=\
  com.xxx.config.MyEnvironmentPostProcessor
  
3,单服务重启后才生效,或者微服务加热加载

你可能感兴趣的:(spring,数据库,sql)