本文介绍如何将 Spring Boot 应用的 application.properties 配置迁移到数据库中,实现动态配置加载,无需每次修改配置后都重启服务器。通过自定义 PropertySource,从数据库读取配置信息,并将其添加到 Spring Boot 的环境属性中,从而实现配置的动态更新和管理。
以下步骤详细介绍了如何从数据库加载 Spring Boot 应用的配置:
1. 创建配置实体类 DynamicConfig
首先,我们需要创建一个实体类,用于映射数据库中的配置信息。该实体类包含配置的键和值。
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
@Setter
@Getter
@Entity
@Table(name = "t_dynamic_config")
public class DynamicConfig {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String key;
private String value;
}2. 创建数据访问接口 DynamicConfigDao
接下来,我们需要创建一个数据访问接口,用于从数据库中读取配置信息。
import org.springframework.data.jpa.repository.JpaRepository; public interface DynamicConfigDao extends JpaRepository{ DynamicConfig findByKey(String key); }
3. 创建自定义 PropertySource 类 DynamicConfigPropertySource
我们需要创建一个自定义的 PropertySource 类,用于从数据库中读取配置信息,并将其添加到 Spring Boot 的环境属性中。
import org.springframework.core.env.EnumerablePropertySource; public class DynamicConfigPropertySource extends EnumerablePropertySource{ public DynamicConfigPropertySource(String name, DynamicConfigDao source) { super(name, source); } @Override public String[] getPropertyNames() { return getSource().findAll().stream().map(DynamicConfig::getKey).toArray(String[]::new); } @Override public Object getProperty(String name) { DynamicConfig config = getSource().findByKey(name); return config != null ? config.getValue() : null; } }
4. 将 PropertySource 添加到 Spring Boot 环境中
最后,我们需要将自定义的 PropertySource 添加到 Spring Boot 的环境中。
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Component;
import org.springframework.core.env.ConfigurableEnvironment;
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Component
static class ConfigDynamicConfigPropertySource implements SmartInitializingSingleton {
@Autowired
private ConfigurableEnvironment environment;
@Autowired
private DynamicConfigDao dynamicConfigDao;
@Override
public void afterSingletonsInstantiated() {
environment.getPropertySources().addLast(new DynamicConfigPropertySource("db_source",dynamicConfigDao));
}
}
}
注意事项
总结
通过自定义 PropertySource,我们可以轻松地从数据库中加载 Spring Boot 应用的配置信息,实现动态配置加载。这种方式可以避免每次修改配置后都重启服务器,提高开发效率。此外,将配置信息存储在数据库中,也方便进行统一管理和维护。