title: Adding @WebFilter and @Component annotation to Spring Filter
body: <p>I have a Filter class 'MyFilter' that is registered via <code>@WebFilter</code>annotation.In the <code>doFilter()</code> I need an object of a <code>MyBeanClass</code> that I have created  in my project. If I create this object via new operator, and run the project on tomcat, I see that the filter is registered once and is working fine.</p>
  
  <p>However, When I try to Autowire the object by adding <code>@Component</code> annotation above the <code>MyFilter</code> class, and then run the project on tomcat, I see that the filter is registered twice.The <code>doFilter()</code> is called twice and the second time <code>doFilter()</code> is called the object of <code>MyBeanClass</code> is not initialized and is <code>null</code>. Hence the <code>NullPointerException</code>.</p>
  
  <p>I need to leave the dependency injection upto Spring and thus Autowiring the object is needed.The concern is -</p>
  
  <ol>
  <li>Why is the filter registered twice.</li>
  <li>Why is the object null the second time.</li>
  <li>What is the correct way of achieving this.</li>
  </ol>
  
  <p>Here is the sample code : 
  MyFilter.java :</p>
  
  <pre><code>@Component
  @WebFilter(filterName = "RestFilter", urlPatterns = { "/*" })
  public class MyFilter implements Filter {
  
      @Autowired
      MyBeanClass myBeanClass;
  
      @Override
      public void init(FilterConfig filterConfig) throws ServletException {
          //this is how I know that filter is registered twice.
          System.out.println("this is init.");  
      }
  
      @Override
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
              throws IOException, ServletException {
          if (myBeanClass.isValidRequest()) {
              System.out.println("Let this request pass");
              chain.doFilter(request, response);
          }
          else{
              System.out.println("Should not let pass this request");
          }
      }
  
      @Override
      public void destroy() {
          // TODO Auto-generated method stub
  
      }
  }
  </code></pre>
  
  <p>MyBeanClass.java</p>
  
  <pre><code>@Component
  public class MyBeanClass{
  
      Boolean valid = false;
  
      public boolean isValidRequest(){
          //some code
      }
  
      //
      //Other piece of code
      //
  }
  </code></pre>
  
  <p>I am new to Spring framework, and have recently started working on a project in Spring. Please correct me if I am doing anything wrong. Or if there is another way of doing this, direct me to right resource.</p>