implementing ApplicationContextAware - ApplicationContext is NULL

前端 未结 2 1150
伪装坚强ぢ
伪装坚强ぢ 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:54

    The culprit is addFilter(..) method of MyAppSpringBoot.

    If you look closely at this LOC FilterRegistration.Dynamic registration = container.addFilter("u3rAuthentication", UserDbAuthenticationFilter.class); it will be evident that even though the UserDbAuthenticationFilter is registered with ServletContext as filter, it is not associated with spring context in any way (since the class is directly registered and not the spring bean which will explain the null references of ApplicationContext and emf respectively).

    Although same class UserDbAuthenticationFilter is scanned by spring and registered as bean later but is not associated with ServletContext as filter (this bean is never invoked as it is not registered as filter and this is where you see your ApplicationContext being set while debugging)

    So there are two instances for same class UserDbAuthenticationFilter one as filter with servlet and another as spring bean with no association / link with each other.

    What you need here is a filter registered with servlet container which is a spring bean as well. GenericFilterBean comes to your rescue. Extend it as per your need and be aware of the below gotcha (from API docs)

    This generic filter base class has no dependency on the Spring ApplicationContext concept. Filters usually don't load their own context but rather access service beans from the Spring root application context, accessible via the filter's ServletContext (see WebApplicationContextUtils).

    Hope this helps. Let know in comments in case you face any issues / need further help.

提交回复
热议问题