Spring Boot:从数据库中检索配置 [英] Spring Boot: Retrieving configuration from a database

查看:38
本文介绍了Spring Boot:从数据库中检索配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能就我实现这一目标的最佳方式提供一些指导.

Can anyone offer me some guidance on the best way for me to achieve this goal.

我想扩展 Spring Boot 外部化配置 这样我就有了一个可以从我的应用程序的任何地方调用的方法.此方法将使用键检索属性值.此方法将首先询问一个数据库表,如果它没有找到指定的键,它将返回到 1.

I'd like to extend the Spring Boot Externalized Configuration so that I have a single method which can be called from anywhere in my application. This method will retrieve a property value using a key. This method will first interrogate a database table and if it does not find the specified key it will then fall back on the PropertySource order described in 1.

所以我有一个类似于:

@Service
public class ConfigurationService {

    private final ConfigurationRepository configurationRepository;

    @Autowired
    public ConfigurationService(ConfigurationRepository configurationRepository) {
        this.configurationRepository = configurationRepository;
    }

    public String getValue(String key) {
        Configuration configuration = configurationRepository.findOne(key);

        // Add something here to get the property from application.properties if the key does not exist in the db

        return configuration == null ? null : configuration.getValue();
    }

}

我可以使用如下:

foo = configuration.getValue("my.property");

有没有更好的方法来解决这个问题?我是否缺少可以使用的 Spring Boot 功能?

Is there a better way of going about this? Am I missing a Spring Boot feature that I could utilise?

我希望能够在应用程序运行时更改属性的值并获取这些新值.

I'd like to be able to change the values of the properties while the application is running and have these new values picked up.

推荐答案

我已经使用 EnvironmentPostProcessor spring 特性来做到这一点.

I have used the EnvironmentPostProcessor spring feature to do this.

你需要像这样创建一个类:

You need to create a class like this:

public class ReadDbPropertiesPostProcessor implements EnvironmentPostProcessor {
    /**
     * Name of the custom property source added by this post processor class
     */
    private static final String PROPERTY_SOURCE_NAME = "databaseProperties";
    
    /**
     * Adds Spring Environment custom logic. This custom logic fetch properties from database and setting highest precedence
     */
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Map<String, Object> propertySource = new HashMap<>();

        try {
            // Build manually datasource to ServiceConfig
            DataSource ds = DataSourceBuilder
                    .create()
                    .username(USERNAME) // replace with your config
                    .password(PASSWORD) // replace with your config
                    .url(DATASOURCE-URL)// replace with your config
                    .driverClassName(DRIVER) // replace with your config
                    .build();

            // Fetch all properties
            PreparedStatement preparedStatement = ds.getConnection().prepareStatement("SELECT name, value FROM propertyConfig WHERE service = ?");
            preparedStatement.setString(1, APP_NAME);
            
            ResultSet rs = preparedStatement.executeQuery();

            // Populate all properties into the property source
            while (rs.next()) {
                String propName = rs.getString("name");
                propertySource.put(propName, rs.getString("value"));
            }
            
            // Create a custom property source with the highest precedence and add it to Spring Environment 
            environment.getPropertySources().addFirst(new MapPropertySource(PROPERTY_SOURCE_NAME, propertySource));
        
        } catch (Exception e) {
            throw new RuntimeException("Error fetching properties from db");
        }
    }
}

由于您需要在 spring 的早期阶段运行该类,因此您需要创建文件 spring.factories 并注册您的环境后处理器.此文件需要位于此处:

Since you need to run this class at a very early stage of spring, you need to create the file spring.factories and register your environment post processor. This file needs to be located here:

src/main/resources/META-INF/spring.factories

在您需要将类设置为 spring 属性的内容中:

In the content you need to set your class to the spring property:

# Environment Post Processor
org.springframework.boot.env.EnvironmentPostProcessor=com.your.package.ReadDbPropertiesPostProcessor

这篇关于Spring Boot:从数据库中检索配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆