如何在SpringBoot的 過濾器之中注入Bean對象

我創建一個全局攔截器,此攔截器主要用於攔截APP用戶登陸和請求API時候,必須加密,我把它命名爲SecurityFilter,它繼承了Filter,web應用啓動的順序是:listener->filter->servlet,

而由於項目應用了SpringBoot,因此咱們項目啓動時,先初始化listener,所以註解的bean會被初始化和注入;而後再來就filter的初始化,再接着纔到咱們的dispathServlet的初始化,所以,當咱們須要在filter裏注入一個註解的bean時,就會注入失敗,由於filter初始化時,註解的bean還沒初始化,無法注入。

那麼,解決方法以下:

    @Bean
    public FilterRegistrationBean securityFilterRegistration() {
            FilterRegistrationBean registration = new FilterRegistrationBean();        
        DelegatingFilterProxy httpBasicFilter = new DelegatingFilterProxy();
        registration.setFilter(httpBasicFilter);
        Map<String,String> m = new HashMap<String,String>();
        m.put("targetBeanName","securityFilter");
        m.put("targetFilterLifecycle","true");
        registration.setInitParameters(m);           
        registration.addUrlPatterns("/appapi/*");
     
        registration.setOrder(2);
        return registration;
    }

這樣你就能夠在securityFilter 裏面添加@Autowired下的bean了。

    @Autowired
    private PermissionUserService userService;

以上事項方式會全局過濾,此過濾不起做用適合於全局過濾(/*);

registration.addUrlPatterns("/appapi/*");

建議使用以下方式

    @Bean
    public FilterRegistrationBean securityFilterRegistration() {
            FilterRegistrationBean registrationBean = new FilterRegistrationBean();
            registrationBean.setFilter(securityFilterBean());
            registrationBean.addUrlPatterns("/appapi/*");
            registrationBean.setName("securityFilter");
            registrationBean.setOrder(2);
            return registrationBean;
        }
        
    @Bean
    public Filter securityFilterBean() {
     return new SecurityFilter();
    }

參考文章:

https://blog.csdn.net/xiaoyi52/article/details/76686001

https://blog.csdn.net/cutterwolf/article/details/77849158

https://blog.csdn.net/u013076044/article/details/72903130

https://blog.csdn.net/angel708884645/article/details/51148865

如何在servlet取得spring beans (autowired)

https://blog.csdn.net/axzywan/article/details/8056892

非spring組件servlet、filter、interceptor中注入spring bean

https://www.cnblogs.com/duanxz/p/5463230.html
---------------------
版權聲明:本文爲CSDN博主「蜀山雪松」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處連接及本聲明。
原文連接:https://blog.csdn.net/jianxia801/article/details/79807917html

相關文章
相關標籤/搜索