Bill Chai
Bill Chai

Reputation: 13

Injection Dependency of spring boot filter usage

I'm practicing spring boot API access token project and here is my question.

Here is my filter file and I'm trying to extends OncePerRequestFilter and inject three arg in to the filter using @RequiredArgsConstructor annotation.

@Component
@RequiredArgsConstructor
public class LogInFilter extends OncePerRequestFilter {

  private final OAuthService oAuthService;
  private final AccessTokenService accessTokenService;
  private final ObjectMapper mapper;

Here is the @Bean

@Configuration
public class ApplicationConfig {

@Bean
  public FilterRegistrationBean logInFilter() {
    ObjectMapper mapper = new ObjectMapper();
    FilterRegistrationBean bean = new FilterRegistrationBean(new LogInFilter());
    bean.addUrlPatterns("/test/api");
    bean.setOrder(Integer.MIN_VALUE);
    return bean;
  }

and I have no idea how to put this three arg as constructor in to new LogInFilter() above

Upvotes: 1

Views: 808

Answers (1)

M. Deinum
M. Deinum

Reputation: 125312

Do this

@Bean
public FilterRegistrationBean logInFilterRegistration(LogInFilter logInFilter) {
  FilterRegistrationBean bean = new FilterRegistrationBean(logInFiliter);
  bean.addUrlPatterns("/test/api");
  bean.setOrder(Integer.MIN_VALUE);
  return bean;
}

Your filter is annotated with @Component so Spring will automatically create an instance, which you can use like this.

Upvotes: 3

Related Questions