java filter过滤器 读取配置文件properties的值

发布时间 2023-05-06 16:53:59作者: 四海骄阳

http://www.yayihouse.com/yayishuwu/chapter/2981

1.获取application.properties的值

如userId=1

 

2.一般实体中采用@Value既可获取

@Value("userIdl")

private String userId;

 

但是在filter中,需要用上下文对象来获取

filter的生命周期如下:

web应用程序启动时,web服务器将创建Filter的实例对象

并调用其init方法,完成对象的初始化功能

从而为后续的用户请求作好拦截的准备工作

filter对象只会创建一次,init方法也只会执行一次

也就是程序刚刚启动的时候 filter就被加载了 这个时候配置文件还没有被加载到

 

3.java filter过滤器 读取配置文件properties的值

 

private String userId;

 

@Override

public void init(FilterConfig arg0) {

   // TODO Auto-generated method stub

   ServletContext servletContext = arg0.getServletContext();

   WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);

   //userId为配置文件的键

   userId= ctx.getEnvironment().getProperty("userId");

}