将@ConfigurationProperties绑定到用于创建bean的构建器 [英] Binding @ConfigurationProperties to builder used to create bean

查看:85
本文介绍了将@ConfigurationProperties绑定到用于创建bean的构建器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建多个咖啡因缓存,例如:

I'm creating multiple Caffeine caches like:

@Bean
public Cache<String, Customer> customerCache() {
    return Caffeine.newBuilder()
            .maximumSize(10_000)
            // other config settings
            .build(..);
}

现在,我想使用 @ConfigurationProperties(prefix ="cache.customer")之类的东西来设置构建器配置选项.

Now I would like to use something like a @ConfigurationProperties(prefix = "cache.customer") to set the builder config options.

其中存在应用程序属性 cache.customer.maximum-size:1000 .

Where a application property cache.customer.maximum-size: 1000 exists.

我可以执行一些巧妙的操作来将 @ConfigurationProperties 映射到Caffeine构建器吗?

Is there something smart I can do to map the @ConfigurationProperties to the Caffeine builder?

推荐答案

您可以执行类似于引导团队对DataSourceProperties所做的操作:

You can do something similar to what the boot team has done with DataSourceProperties:

您将属性绑定到一个属性类中,然后在该属性类上使用一个方法来创建您的构建器.

You bind your properties into a property class and then use a method on that properties class to create your builder.

这是另一个示例,其中我们将属性和数据源都绑定到同一根:

Here is a different example where we are binding both the properties and a data source to the same root:

    @Bean
    @ConfigurationProperties("datasource.task")
    public DataSourceProperties taskDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name = {"taskDataSource"}, destroyMethod="")
    @ConfigurationProperties("datasource.task")
    @ConditionalOnMissingBean(name="taskDataSource")
    public DataSource taskDataSource() {
        return taskDataSourceProperties().initializeDataSourceBuilder().build();
    }

这篇关于将@ConfigurationProperties绑定到用于创建bean的构建器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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