我在Web Filter中发现,无法初始化自动装配的bean,如下面的代码
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
public class ClientIpFilter implements Filter {
@Autowired
private Environment environment;
}
在配置中注册Bean
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@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在其他bean之前被引用了吗?如果是,我怎样才能在网络过滤器中使用spring bean?
答案 0 :(得分:0)
您错过了ClientIpFilter类的@Component
注释。