如何从数据库中获得配置信息

在java开发中会有多个环境都配置,我们如何把不同环境都配置信息保存到数据库,在springboot启动时如何从数据库中加载配置信息,代码如何实现

在Java开发中,我们可以使用数据库来保存不同环境的配置信息,然后在Spring Boot应用启动时从数据库中加载配置信息。下面是实现步骤:

创建一个数据库表,用于保存不同环境的配置信息,例如:

CREATE TABLE `config` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `env` varchar(50) NOT NULL COMMENT '环境名称',
  `property_key` varchar(50) NOT NULL COMMENT '配置项的键',
  `property_value` varchar(200) NOT NULL COMMENT '配置项的值',
  PRIMARY KEY (`id`),
  KEY `idx_env_key` (`env`,`property_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='配置信息表';

在Spring Boot应用的配置文件中,配置数据源的连接信息和JPA相关信息,例如:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

创建一个实体类,用于映射配置信息表中的数据,例如:

package com.example.demo.entity;

import lombok.Data;

import javax.persistence.*;

@Data
@Entity
@Table(name = "config")
public class Config {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String env;
    @Column(name = "property_key")
    private String key;
    @Column(name = "property_value")
    private String value;
}

创建一个Repository接口,用于访问数据库中的配置信息,例如:

package com.example.demo.repository;

import com.example.demo.entity.Config;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ConfigRepository extends JpaRepository<Config, Integer> {
    List<Config> findByEnv(String env);
}

创建一个Service类,用于从数据库中加载配置信息,例如:

package com.example.demo.service;

import com.example.demo.entity.Config;
import com.example.demo.repository.ConfigRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ConfigService {
    @Autowired
    private ConfigRepository configRepository;

    public Map<String, String> getConfig(String env) {
        List<Config> configList = configRepository.findByEnv(env);
        Map<String, String> configMap = new HashMap<>();
        for (Config config : configList) {
            configMap.put(config.getKey(), config.getValue());
        }
        return configMap;
    }
}

在应用启动时,调用ConfigService类的getConfig方法,将获取到的配置信息保存到Spring Boot的Environment中,例如:

package com.example.demo;

import com.example.demo.service.ConfigService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;

import java.util.Map;
import java.util.Properties;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();
        ConfigService configService = applicationContext.getBean(ConfigService.class);
        Map<String, String> configMap = configService.getConfig("dev");
        Properties properties = new Properties();
        properties.putAll(configMap);
        PropertiesPropertySource propertySource = new PropertiesPropertySource("config", properties);
        propertySources.addLast(propertySource);
    }
}

这样,当应用启动时,就会从数据库中加载配置信息,并将配置信息保存到Spring Boot的Environment中,我们就可以通过@ConfigurationProperties注解来注入这些配置信息了。