美文网首页SpringBoot配置
Springboot中过滤器使用@Value获取配置文件值为nu

Springboot中过滤器使用@Value获取配置文件值为nu

作者: 哭泣哭泣帕拉达 | 来源:发表于2020-04-16 20:41 被阅读0次

在本地开发阶段,过滤器中使用@Value可以正常获取配置文件中的值

application.yaml配置文件如下:

app.system.id=20191010
app.service.secretkey=123456

过滤器配置

@WebFilter(urlPatterns = "/api/*", filterName = "SSOConfig")
public class SSOConfig implements Filter {

     @Value("${app.system.id}")
     private String systemId;
     
     @Value("${app.service.secretkey}")
     private String secretKey;
     
     @Override
     public void init(FilterConfig filterConfig) throws ServletException {

     }
        
     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        
        //本地开发阶段是可以获取到值得
        System.out.println(systemId);
        System.out.println(secretKey);
        filterChain.doFilter(request, response); 
     }
     @Override
     public void destroy() {

     }
}

但是打成war包放在tomcat或金蝶apusic应用服务器上,@Value注入的值获取不到,systemId和secretKey都为null。这是因为先加载filter,然后再加载spring,所以注入的值为null,使用@Autowired注入bean的话,也是注入不了,值也为null。可以使用static变量,然后再为变量赋值的方法实现。

@Component
public class SSOUtil {

    public static String systemId;
    
    public static String secretKey;

    @Value("${app.system.id}")
    public void setSystemId(String systemId) {
        SSOUtil.systemId=systemId;
    }

    @Value("${app.service.secretkey}")
    public void setSecretKey(String secretKey) {
        SSOUtil.secretKey=secretKey;
    }
    
    public static String getApp() {
        return systemId+":"+secretKey;
    }
}
@WebFilter(urlPatterns = "/api/*", filterName = "SSOConfig")
public class SSOConfig implements Filter {
     
     @Override
     public void init(FilterConfig filterConfig) throws ServletException {

     }
        
     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        
        System.out.println(SSOUtil.getApp());
        filterChain.doFilter(request, response); 
     }
     @Override
     public void destroy() {

     }
}

相关文章

网友评论

    本文标题:Springboot中过滤器使用@Value获取配置文件值为nu

    本文链接:https://www.haomeiwen.com/subject/axxjvhtx.html