Search code examples
springspring-data-jpatuckey-urlrewrite-filter

How to inject a Spring Data JPA Repository into a Servlet Filter?


I'm using the Tuckey UrlRewriteFilter. I want to use a rewrite rule from a database, so using the <class-rule class="com.example.Foo" /> configuration, which lets you get rules at runtime. I created a class extending RewriteRule:

public class Foo extends RewriteRule {

  @Autowired
  private MyRepository myRepository;

  public boolean init(ServletContext servletContext) {

    return true;
  }

  @Override
  public RewriteMatch matches(HttpServletRequest request, HttpServletResponse response) {

    //myRepository is null

    return super.matches(request, response);
  }

  @Override
  public void destroy() {

  }
}

I'd like to use a Spring Data JPA Repository inside this Foo class, but it looks the repository is null.

How can I inject it correctly?


Solution

  • Declare your filter in web.xml as usual, except that you will need to provide org.springframework.web.filter.DelegatingFilterProxy as the filter class name instead of your actual class name.

    <filter>
      <filter-name>urlRewriteFilter</filter-name>
      <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
      <init-param>
          <param-name>targetFilterLifecycle</param-name>
          <param-value>true</param-value>
      </init-param>
    </filter>
    <filter-mapping>
      <filter-name>urlRewriteFilter</filter-name>
      <url-pattern>/</url-pattern>
    </filter-mapping>
    

    Finally, in your ROOT application context, declare a bean pointing to your filter class and with the same name as the filter name provided in web.xml in the application context file loaded from web.xml:

    <bean id="urlRewriteFilter" class="org.tuckey.web.filters.urlrewrite.UrlRewriteFilter"/>
    

    Since your filter instance is now managed by Spring, you can inject any Spring managed bean into it.