1尝试一:
1)直接继承RedisHttpSessionConfiguration,因为注解@EnableRedisSession这个注解接口,其实也是实现了它,这里因为出现了又一个同类型的Bean RedisOperationsSessionRepository,所以配置文件要写上:
spring.main.allow-bean-definition-overriding=true
redis.maxInactiveIntervalInSeconds=30
否则报错,已存在同类型bean
2)如果不继承RedisHttpSessionConfiguration,而直接开始定义bean,报错bean间循环注入
3)这里这个配置是早于applicaitonContext,environment的,所以这里从配置文件取值为null
4)虽然定义的这个bean不报错,但是debug下,并未进入
@Slf4j
@Configuration
public class RedisSessionConfig2 extends RedisHttpSessionConfiguration{
@Value("${redis.maxInactiveSeconds}")
private Integer maxInactiveSeconds;
@Bean
public static ConfigureRedisAction configureRedisAction() {
return ConfigureRedisAction.NO_OP;
}
@Primary
@Bean
public RedisOperationsSessionRepository sessionRepository(RedisOperationsSessionRepository rs){
rs.setDefaultMaxInactiveInterval(maxInactiveSeconds);
log.info("maxinactive seconds="+maxInactiveSeconds);
return rs;
}
}
尝试二:
既然@EnableRedisSession注解把参数值写死了,那是否可以照着它自定义一个注解类呢,然后在需要的地方注解上
错误一:这里注入值是失败的
错误二:RedisHttpSessionConfiguration在引入它时去固定检查@EnableRedisSession,如果引入了但不是通过@EnableRedisSession注解引入的RedisHttpSessionConfiguration,就会报错空指针
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({RedisHttpSessionConfiguration.class})
@Configuration
public @interface EnableCustomRedisHttpSession {
@Value("redis.timeout")
int maxInactiveIntervalInSeconds() default 1800;
String redisNamespace() default "spring:session";
RedisFlushMode redisFlushMode() default RedisFlushMode.ON_SAVE;
String cleanupCron() default "0 * * * * *";
}
尝试三:通过构造函数,另外值的获取只能通过文件获取方式,不能依赖于注入 ok了
@Configuration
public class RedisSessionConfig2 extends RedisHttpSessionConfiguration{
@Bean
public static ConfigureRedisAction configureRedisAction() {
return ConfigureRedisAction.NO_OP;
}
public RedisSessionConfig2() {
super();
String ts= PropertyFile.getProperties().getProperty("redis.maxInactiveIntervalInSeconds");
super.setMaxInactiveIntervalInSeconds(Integer.valueOf(ts));
}
}
public class PropertyFile {
private static Properties pro;
static {
//本地测试则为classpath=resources
//test环境,设置classpath=config/.
String path="application.properties";
ClassLoader classLoader = PropertyFile.class.getClassLoader();
InputStream inputStream =classLoader.getResourceAsStream(path);
try {
pro = new Properties();
pro.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Properties getProperties() {
return pro;
}
}