我有以下课程:
@EnableRedisIndexedHttpSession(maxInactiveIntervalInSeconds = 2000)
public class MyApplication {
我想输入
maxInactiveIntervalInSeconds
Spring 属性文件中的值(而不是硬编码的 2000
)。我不能在那里使用@Value。
有什么想法吗?
提前致谢!
正如文件所说
更高级的配置可以扩展 改为 RedisIndexedHttpSessionConfiguration。
尝试创建自己的配置来覆盖
RedisIndexedHttpSessionConfiguration
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(MyRedisSessionProperties.class)
public class CustomRedisIndexedHttpSessionConfiguration extends RedisIndexedHttpSessionConfiguration {
private final MyRedisSessionProperties myRedisSessionProperties;
@Autowired
void customize(MyRedisSessionProperties properties) {
setMaxInactiveIntervalInSeconds((int) properties.getMaxInactiveInterval().getSeconds());
}
@ConfigurationProperties("my.redis.session")
static class MyRedisSessionProperties {
private Duration maxInactiveInterval;
public Duration getMaxInactiveInterval() {
return this.maxInactiveInterval;
}
public void setMaxInactiveInterval(Duration maxInactiveInterval) {
this.maxInactiveInterval = maxInactiveInterval;
}
}
}
应用程序.属性
my.redis.session.max-inactive-interval=1h
从技术上来说,甚至比这简单得多。
我假设您正在使用 Spring Boot,因此我们将参考
3.2.0-RC1
Spring 位(Spring Boot 和 Spring Session)。早期版本,尤其是 3.x
系列,在功能上应该是相同的。
您当然不想养成直接扩展 Redis 的 Spring Session
RedisIndexedHttpSessionConfiguration
类 (Javadoc) 的习惯,部分原因是这正是 @EnableRedisIndexedHttpSession
注释“导入”的类 (Javadoc ),Spring Session 和 Spring Boot 都使“定制”变得容易。
弹簧启动方式:
您可以简单地在 Spring Boot 中设置以下属性
application.properties
:
# Your Spring Boot / Spring Session application.properties
spring.session.timeout=2000s
请参阅 Spring Boot 文档,了解
spring.session.timeout
属性。
Spring Boot使用的fallback属性是:
server.servlet.session.timeout
这从 Spring Boot 自动配置中可以明显看出(source)。
Spring 会话方式(无 Spring Boot):
当你不使用 Spring Boot 时,这甚至更简单。只需从 Spring Session 注册一个类型为
SessionRepositoryCustomizer
(Javadoc) 的 bean,如下所示:
@EnableRedisIndexedHttpSession
class CustomSpringSessionConfiguration {
@Bean
SessionRepositoryCustomizer<RedisIndexedSessionRepository> customizer(
@Value("${my.session.timeout:2000}") int sessionTimeoutSeconds) {
return repository ->
repository.setDefaultMaxInactiveInterval(sessionTimeoutSeconds);
}
}
注意:事实上,上面的 Spring Session 定制配置代码正是 Spring Boot 本身所做的,当然,还考虑了其他 Spring [Web [Session]] 配置;再次查看完整的来源。
然后,您的
my.session.timeout
属性可以从 Spring 的 Environment
支持的任何位置配置为“属性源”,包括但不限于:Java 系统属性、属性文件、环境变量等,包括您的根据需要自己定制实现,这与 Spring Boot 已经为您提供的类似。