Parameswar
Parameswar

Reputation: 2079

Injecting a service in spring boot filter

Have a filter where a service is autowired. I am injecting the service as constructor argument - from the config where filter is registered.

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;
    }
}

I kind of felt autowiring from config might not be good. Is there any other better way ?

Upvotes: 1

Views: 3910

Answers (1)

Michael
Michael

Reputation: 44250

If MyFilter is only constructed once (a singleton) then it can be a component, which means it will be autowired implicitly.

@Component
MyFilter implements Filter {
    private final ServiceToBeInjected;

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

Your bean can then take the filter as a method parameter

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

If MyFilter needs to be constructed more than once then what you've done is fine.

Upvotes: 2

Related Questions