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

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

问题描述

任何人都可以向我提供一些有关实现该目标的最佳方法的指导.

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

我想扩展Spring Boot 外部配置,这样我就可以在应用程序中的任何位置调用一个方法.此方法将使用键检索属性值.此方法将首先查询数据库表,如果未找到指定的键,则它将退回到

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.

所以我会提供类似的服务:

So I'd have a service similar to:

@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.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/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天全站免登陆