Web过滤器无法读取Spring引导中的Property文件

时间:2017-03-21 14:32:12

标签: spring-boot

我有简单的ip过滤器,它会过滤不在白名单中的ips。 代码很简单,比如

@EnableConfigurationProperties(AppProperties.class)
public class ClientIpFilter implements Filter {

    @Autowired
    private AppProperties appProperties;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        HashSet<String> trustedIps = loadAccessIPList();
        HttpServletRequest req = (HttpServletRequest) request;
        Map<String, String> headerMap = new HashMap<String, String>();
        Enumeration<String> headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String str = (String) headers.nextElement();
            headerMap.put(str, req.getHeader(str));
        }
.............

}

我定义了一个配置以包含它。

@Configuration
public class CustomWebSecurityConfigurerAdapter {
     @Bean
        public FilterRegistrationBean filterRegistrationBean() {
            FilterRegistrationBean registrationBean = new FilterRegistrationBean();
            ClientIpFilter securityFilter = new ClientIpFilter();
            registrationBean.setFilter(securityFilter);
            registrationBean.setOrder(1);
            return registrationBean;
        }   
}

但是Filter不能自动装配AppProperties,其中包括来自我的application.preperties的配置。

2 个答案:

答案 0 :(得分:1)

您的AppProperties文件应如下所示,带有注释和适当的前缀,如application.properties文件中所述

@Configuration
@ConfigurationProperties(prefix = "com.test")

public class AppProperties {

private String name;

private String age;


}

ClientFilter类中不应该要求@EnableConfigurationProperties。只需自动装配属性文件即可。

答案 1 :(得分:0)

我找到了根本原因。我需要让ClientIpFilter成为一个组件,以便它可以自动装配,然后spring可以注册其他属性。

@Component
@EnableConfigurationProperties(AppProperties.class)
public class ClientIpFilter implements Filter {
@Autowired
private AppProperties appProperties;

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    // TODO Auto-generated method stub
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
        ServletException {
    HashSet<String> trustedIps = loadAccessIPList();
    HttpServletRequest req = (HttpServletRequest) request;
    Map<String, String> headerMap = new HashMap<String, String>();

.............

}