filter未注册到spring的容器中,获取配置文件中的参数获取不到
第一种尝试
采用下面的方法获取不到
ContextLoader.getCurrentWebApplicationContext().getEnvironment().getProperty("xxx");
加载filter的时候spring还未初始化配置文件中的值
然后通过在filter中添加@compent 在结合@value(“${xxx}”)也不行,还是上述的原因导致
第二种尝试
当我通过实体类配置进行读取配置文件,然后将这个实体类通过springcontext去读取时会报下面的错误
@Component
public class IdpConfig {
@Value("${kickout.notify.tacs.sleepTime:10}")
private String sleepTime;
public String getSleepTime() {
return sleepTime;
}
}
然后再filter中使用
ContextLoader.getCurrentWebApplicationContext().getBean("idpConfig", IdpConfig.class);
启动会报如下错误,还是相当于加载不到配置
java.lang.IllegalStateException: org.springframework.context.support.GenericApplicationContext@76f9b69c has not been refreshed yet
at org.springframework.context.support.AbstractApplicationContext.assertBeanFactoryActive(AbstractApplicationContext.java:1141)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1153)
第二种尝试错误是因为项目中没有正确的注入到spring中,导致出现问题,重新使用xml的配置后可以正常的获取值
第三种尝试
使用xml的配置方法,先用spring实例化后赋值给一个变量,再赋值给静态变量全局共享另一个变量
<bean id="xxxfilter" class="xxxx" init-method="initBean">
<property name="sleepTimeSource" value="${kickout.notify.tacs.sleepTime:10}"/>
</bean>
将xml种的值注入到filter中,当实例化这个filter时就将获取到的参数赋值给静态变量,由于静态变量是全局共享的,因此在容器中使用这个变量时是有值的,这个可以达到获取值的目的
private static Long sleepTime;
private Long sleepTimeSource;
public Long getSleepTimeSource() {
return sleepTimeSource;
}
public void setSleepTimeSource(Long sleepTimeSource) {
this.sleepTimeSource = sleepTimeSource;
}
public void initBean() {
sleepTime = this.sleepTimeSource;
}
总结,这个问题的关键原因是spring的加载filter和serverlet加载filter是不同的实例,如果交给spring管理来获取配置文件中的值,但是使用的时候需要传递给serverlet来获取