在Spring Boot过滤器中注入服务

时间:2018-11-12 08:43:59

标签: java spring-boot dependency-injection autowired

有一个自动连接服务的过滤器。 我将服务作为构造函数参数注入-从注册过滤器的配置中获取。

MyFilter implements filter {
    private final ServiceToBeInjected serviceToBeInjected;

    public MyFilter(ServiceToBeInjected serviceToBeInjected) {
        this.serviceToBeInjected = serviceToBeInjected;
    }
}

public class ConfigClass {
    private final ServiceToBeInjected serviceToBeInjected;

    @Autowired
    public ConfigClass(ServiceToBeInjected serviceToBeInjected) {
        this.serviceToBeInjected = serviceToBeInjected;
    }

    @Bean
    public FilterRegistrationBean<MyFilter> filterRegistrationBean() {
        final FilterRegistrationBean<MyFilter> filterRegBean = new FilterRegistrationBean<>();
        filterRegBean.setFilter(new MyFilter(serviceToBeInjected));
        filterRegBean.addUrlPatterns(");    
        return filterRegBean;
    }
}

我觉得从config自动布线可能不是一件好事。 还有其他更好的方法吗?

1 个答案:

答案 0 :(得分:0)

如果MyFilter仅构造一次(单例),则它可以是一个组件,这意味着它将隐式地自动接线。

@Component
MyFilter implements Filter {
    private final ServiceToBeInjected;

    // Autowired implicitly
    public MyFilter(ServiceToBeInjected serviceToBeInjected) {
        this.serviceToBeInjected = serviceToBeInjected;
    }
}

您的bean然后可以将过滤器作为方法参数

public class ConfigClass {
    @Bean
    public FilterRegistrationBean<MyFilter> foo(final MyFilter filter) {
        final FilterRegistrationBean<MyFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(filter);
        bean.addUrlPatterns("");
        return bean;
    }
}

如果MyFilter需要多次构建,那么您所做的一切就很好了。