Question

I am a newbie and going through spring learning curve and i have a question to understand what cases i will be using code based servlet container initialization against xml initialization in web descriptor file.

The reason for my question is, at this time i wanted to spend time in learning what is used most of the time rather overloading many concepts which might be provided with the framework just for flexibility.

Any advice? Thanks for reading

Was it helpful?

Solution

The main reason you'd want to use Java based container initialization is when you want to register Spring managed Servlet, Filter, and XxxListener objects.

For example, when you want to register a ServletContextListener, you specify

<listener>
    com.your.listeners.MyListener
</listener>

in the deployment descriptor. The container takes that fully qualified class name and uses reflection to find the corresponding Class object which it instantiates to get an instance. In other words, the object is uniquely managed by the container. You can't have Spring inject fields easily.

On the other hand, with a ServletContainerInitializer, or the corresponding Spring class, you can specify Servlet, Filter, or Listener beans in your Spring context (either through XML or @Configuration classes) and register those Spring-managed instances directly through the ServletContext.


Note that there are still some configurations for which you need to use the deployment descriptor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top