我在 Web 过滤器中发现,自动连线的 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;
}
}
这是因为过滤器是在其他 Bean 之前启动的吗?如果是,如何在网络过滤器中使用春豆?
您错过了 ClientIpFilter 类@Component
注释。