Search code examples
javaspringtomcatservlet-filterscatalina

Does Spring setup the application context before the container initializes its filters?


I'm using Spring's DelegatingFilterProxy to use a Spring bean as a container filter. In order to use the init and destroy methods from the Filter interface I'm defining targetFilterLifecycle as true.

Does Spring ensure all the dependency injected beans in the filter class are available by the time the container calls the init method or is there a risk that some beans are still not initialized or at least injected?

Also, what was the reasoning behind Spring setting the targetFilterLifecycle default as false?


Solution

  • Spring loads its application context through the ContextLoaderListener which is a ServletContextListener (part of the Servlet API). All registered ServletContextListener and other listener types are initialized before any declared Filters and Servlets.

    As such, and assuming you set targetFilterLifecycle to false, by the time your DelegatingFilterProxy is created by the Servlet container, your Filter bean is already created and initialized inside the application context (that's where it should be declared).

    The javadoc states the following about targetFilterLifecycle:

    Default is "false"; target beans usually rely on the Spring application context for managing their lifecycle. Setting this flag to "true" means that the servlet container will control the lifecycle of the target Filter, with this proxy delegating the corresponding calls.

    If you set it or leave it as false, Spring will be responsible for initializing the object and doing any bean injection (and/or performing other lifecycle steps). If you set it to true, Spring will give it to the Servlet container to do its own initialization after having done its own. This is done by invoking the init method at startup and the destroy method when shutting down.