【问题标题】:Spring Boot - using Externalized Configuration values in @Configuration classesSpring Boot - 在@Configuration 类中使用外部化配置值
【发布时间】:2015-04-19 03:39:28
【问题描述】:

我需要外部化我们的会话存储,所以使用了 spring-session。

按照他们在https://github.com/spring-projects/spring-session/blob/master/samples/boot/src/main/java/sample/config/EmbeddedRedisConfiguration.java 的示例,我创建了我的EmbeddedRedisConfiguration,一切正常。

我决定在预先存在本地redis服务器的情况下,我希望可选支持指定Redis可执行路径,所以我在/resources/config/application.properties中添加了以下键值redis.embedded.executable.path==/path/to/redis

我的直接想法是在我的配置中使用@Value 注释,并可以访问该值

static class RedisServerBean implements InitializingBean, DisposableBean, BeanDefinitionRegistryPostProcessor {
    private RedisServer redisServer;

    @Value("${redis.embedded.executable.path}")
    String executablePath;

    public void afterPropertiesSet() throws Exception {
        if (executablePath != null) {
            redisServer = new RedisServer(new File(executablePath), Protocol.DEFAULT_PORT);    
        } else {
            redisServer = new RedisServer(Protocol.DEFAULT_PORT);
        }
        redisServer.start();
    }

    public void destroy() throws Exception {
        if(redisServer != null) {
            redisServer.stop();
        }
    }

    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {}

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {}
}

但是,executablePath 始终为空。如您所知,如果您在 @Service 类或等效类中使用 @Value,则会填充该值。

我假设在加载属性的 bean 之前调用此配置,但我也知道这是可能的,因为例如 @DatasourceAutoConfiguration 可以使用 spring.datasource.* 属性

我显然在这里忽略了一些简单的事情。我需要我自己的@ConfigurationProperties

【问题讨论】:

  • 你能告诉我们你的配置文件吗?这个bean实际上是由Spring管理的吗?
  • 此配置文件与上面提供的链接相同,但添加了我的@Value 注释字段
  • 为什么需要BeanDefinitionRegistryPostProcessor?它导致在 @Value 可以绑定之前提前实例化。
  • 就是这样。我想这就是复制粘贴所发生的事情,即使来自官方来源:)

标签: spring spring-boot


【解决方案1】:

将您的属性文件更改为:

redis.embedded.executable.path=/path/to/redis

【讨论】:

  • 我的问题表明我已将此添加到我的application.properties
  • 你有两个等号 kabal
  • 这是吕迪格的答案。 kabal 在属性文件中有错误,我正在修复它
  • 额外的 = 只是配置值错误配置,不是空值的原因。
猜你喜欢
  • 1970-01-01
  • 2019-08-17
  • 2021-01-05
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 2015-03-28
  • 2021-12-16
  • 2014-10-23
相关资源
最近更新 更多