spring-bootspring-sessionspring-data-redisspring-profiles

Set Spring Session Redis on production only


Is it possible to set the Spring session data redis module on production profile only?

I have tried using @Profile but the AbstractHttpSessionApplicationInitializer was initialized before setting the profile/environment and thus will give me an NoSuchBean Exception

NoSuchBeanDefinitionException: No bean named 'springSessionRepositoryFilter' available

And when I try to inject the profile using @Values it returns null value.

@Value("${spring.profiles.active:local}")
private String activeProfile; // result is null

Solution

  • I have solved the problem using this article.

    The production session config will be like this.

    @Configuration
    @ConditionalOnProperty(name = "spring.profiles.active", havingValue = "production")
    @EnableRedisHttpSession
    @ConfigurationProperties(prefix = "redis.db")
    public class ProductionSessionConfig {
    
        @Setter
        private String server;
        @Setter
        private Integer port;
    
        @Bean
        public JedisConnectionFactory connectionFactory() {
            //creates your own connection
            RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(server, port);
            return new JedisConnectionFactory(config);
        }
    
    }
    

    And if you are not going to use the spring-session-data-redis in other environment. You can just proceed. Just keep in mind the @ConditionalOnProperty value.

    And do not forget to exclude the Auto Configuration of Session.

    @SpringBootApplication(exclude = {SessionAutoConfiguration.class})