Spring Boot:从数据库中检索配置

时间:2015-05-13 10:48:58

标签: java spring properties configuration spring-boot

任何人都可以为我提供一些指导,帮助我实现这一目标。

我想扩展Spring Boot Externalized Configuration,以便我有一个方法可以在我的应用程序的任何地方调用。此方法将使用键检索属性值。此方法将首先询问数据库表,如果找不到指定的键,则它将回退到1中描述的PropertySource订单。

所以我的服务类似于:

@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功能吗?

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

1 个答案:

答案 0 :(得分:2)

我使用了EnvironmentPostProcessor spring功能来执行此操作。

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

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并注册环境后处理器。此文件需要位于此处:

src/main/META-INF/spring-factories

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

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