Search code examples
springspring-bootspring-cache

Injecting property value for session timeout in Spring Session annotation


I have the following class:

@EnableRedisIndexedHttpSession(maxInactiveIntervalInSeconds = 2000)
public class MyApplication {

I want to put in maxInactiveIntervalInSeconds a value from the Spring properties file (instead of the hardcoded 2000). I can't use @Value there.

Any idea?

Thanks in advance!


Solution

  • It is technically much simpler than this, even.

    I assume you are using Spring Boot, so we will refer to 3.2.0-RC1 Spring bits (both Spring Boot and Spring Session). Earlier versions, especially in the 3.x line, should functionally be the same.

    You certainly don't want to be in the habit of directly extending the Spring Session for Redis, RedisIndexedHttpSessionConfiguration class (Javadoc), partly because this is precisely the class that the @EnableRedisIndexedHttpSession annotation "imports" (Javadoc), and both Spring Session as well as Spring Boot make "customization" easy.

    SPRING BOOT WAY:

    You can simply set the following property in your Spring Boot application.properties:

    # Your Spring Boot / Spring Session application.properties
    
    spring.session.timeout=2000s
    

    See Spring Boot documentation on the spring.session.timeout property.

    The fallback property used by Spring Boot is:

    server.servlet.session.timeout

    This is evident from the Spring Boot auto-configuration (source).

    SPRING SESSION WAY (without Spring Boot):

    It is even simple when you are not using Spring Boot. Simply register a bean of type SessionRepositoryCustomizer (Javadoc) from Spring Session, like so:

    @EnableRedisIndexedHttpSession
    class CustomSpringSessionConfiguration {
    
        @Bean
        SessionRepositoryCustomizer<RedisIndexedSessionRepository> customizer(
            @Value("${my.session.timeout:2000}") int sessionTimeoutSeconds) {
    
            return repository -> 
                repository.setDefaultMaxInactiveInterval(sessionTimeoutSeconds);   
        }
    }
    

    NOTE: In fact, the Spring Session customization configuration code above is precisely what Spring Boot is doing itself, of course, with other Spring [Web [Session]] configuration taken into account; again see complete source.

    Then, your my.session.timeout property can be configured from any location that Spring's Environment supports as a "property source", including, but not limited to: Java System properties, properties files, Environment variables, and so on, including your own custom implementations as necessary, not unlike what Spring Boot provides for you already as well.