【发布时间】: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