簡體   English   中英

在Spring Filter中添加@WebFilter和@Component批注

[英]Adding @WebFilter and @Component annotation to Spring Filter

我有一個通過@WebFilter注釋注冊的Filter類'MyFilter'。在doFilter()我需要一個在項目中創建的MyBeanClass對象。 如果我通過new運算符創建此對象,然后在tomcat上運行該項目,則會看到該過濾器已注冊一次並且可以正常工作。

但是,當我嘗試通過在MyFilter類上方添加@Component注釋來自動MyFilter對象,然后在tomcat上運行項目時,我看到過濾器已注冊兩次doFilter()被調用兩次,第二次被doFilter()調用被稱為MyBeanClass的對象未初始化,並且為null 因此, NullPointerException

我需要將依賴項注入保留到Spring上,因此需要自動裝配對象。關注的是-

  1. 為什么過濾器注冊了兩次。
  2. 為什么對象第二次為空。
  3. 實現此目標的正確方法是什么?

這是示例代碼:MyFilter.java:

@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

    }
}

MyBeanClass.java

@Component
public class MyBeanClass{

    Boolean valid = false;

    public boolean isValidRequest(){
        //some code
    }

    //
    //Other piece of code
    //
}

我是Spring框架的新手,最近開始在Spring中從事項目。 如果我做錯了什么,請糾正我。 或者,如果還有另一種方法,請引導我使用正確的資源。

這是因為您在Application類上添加了@ServletComponentScan ,並且還在過濾器上使用了@Component 您可以刪除其中任何一個。

順便說一句,如果您使用@component ,則@webfilter將不起作用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM