implementing ApplicationContextAware - ApplicationContext is NULL

前端 未结 2 1153
伪装坚强ぢ
伪装坚强ぢ 2021-01-14 07:14

I\'m programming a Tomcat application which serves as a proxy for some internal services.

I\'ve switched my Spring project from a mixed XML and annotation-based conf

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-14 07:46

    As the application context is correctly injected in your controller, I assume that Spring is correctly initialized. But your filters are declared as raw filters, not as spring beans, so the spring annotations are ignored on them.

    You have two ways to get access to the application context:

    1. a raw filter (not Spring enabled) can get access to the root application context with WebApplicationContext WebApplicationContextUtils.getWebApplicationContext(ServletContext sc). For example, you could change your init method:

      @Override
      public void init(FilterConfig filterConfig)    
      {
          ServletContex sc = filterConfig.getServletContext();
          appContext = WebApplicationContextUtils.getWebApplicationContext(sc);
          logger.debug("Filter {} initialisiert. App-Context: {} {}", this.getClass().getName(),appContext.hashCode(), appContext);
      }
      
    2. you can also use a DelegatingFilterProxy to effectively use beans as filters:

      Change add filter to:

      private void addFilters(ServletContext container) {
          FilterRegistration.Dynamic registration
                  = container.addFilter("u3rAuthentication", DelegatingFilterProxy.class);
          registration.addMappingForUrlPatterns(null, false, "/entry/*");
      
          registration = container.addFilter("responseXmlFilter", DelegatingFilterProxy.class);
          registration.addMappingForUrlPatterns(null, false, "/entry/*");
      }
      

      add filter beans in your root context:

      @Bean
      public UserDbAuthenticationFilter u3rAuthentication() { 
          return new UserDbAuthenticationFilter();
      }
      
      @Bean
      public ResponseTextXmlFilter responseXmlFilter() { 
          return new ResponseTextXmlFilter();
      }
      

      the init method will no longer be called, but this would work:

      @PostConstruct
      public void filterInit() throws ServletException
      {
          logger.debug("Filter {} initialisiert. App-Context: {} {}", this.getClass().getName(),appContext.hashCode(), appContext);
      }
      

提交回复
热议问题